欢迎您访问程序员文章站本站旨在为大家提供分享程序员计算机编程知识!
您现在的位置是: 首页  >  IT编程

java实现简单TCP聊天程序

程序员文章站 2024-02-14 17:39:58
本文实例为大家分享了java实现tcp聊天程序的具体代码,供大家参考,具体内容如下 服务端代码: package com.test.server; im...

本文实例为大家分享了java实现tcp聊天程序的具体代码,供大家参考,具体内容如下

服务端代码:

package com.test.server;
 
import java.io.datainputstream;
import java.io.dataoutputstream;
import java.io.ioexception;
import java.net.serversocket;
import java.net.socket;
 
public class server {
 
 public static void main(string[] args) {
 new server().startserver();
 }
 
 public void startserver(){
 try {
  //服务器在9990端口监听客户端的连接
  serversocket ss = new serversocket(9999);
  system.out.println("server is listening...");
  while(true){
  //阻塞的accept方法,当一个客户端连接上,才会返回socket对象
  socket s = ss.accept();
  system.out.println("a client has connected!");
  //开启线程处理通信
  new communicatethread(s).start();
  }
 } catch (ioexception e) {
  e.printstacktrace();
 }
 }
 
 public class communicatethread extends thread{
 
 socket socket;
 datainputstream dis;
 dataoutputstream dos;
 
 public communicatethread(socket socket){
  this.socket = socket;
  try {
  dis = new datainputstream(socket.getinputstream());
  dos = new dataoutputstream(socket.getoutputstream());
  } catch (ioexception e) {
  e.printstacktrace();
  }
 }
 
 @override
 public void run() {
  super.run();
  //读取客户端发过来的消息
  string msg = null;
  try {
  while((msg = dis.readutf()) != null){
   system.out.println("client send msg :" + msg);
   string replymsg = "server reply : " + msg;
   dos.writeutf(replymsg);
   system.out.println("server reply msg :" + replymsg);
  }
  } catch (ioexception e) {
  e.printstacktrace();
  }
 }
 }
 
}

客户端代码:

package com.test.client;
 
import java.io.datainputstream;
import java.io.dataoutputstream;
import java.io.ioexception;
import java.net.socket;
import java.util.scanner;
 
public class client {
 
 public static void main(string[] args) {
 new client().startclient();
 }
 
 public void startclient(){
 try {
  //连接到服务器
  socket socket = new socket("localhost", 9999);
  datainputstream dis = new datainputstream(socket.getinputstream());
  dataoutputstream dos = new dataoutputstream(socket.getoutputstream());
  scanner scanner = new scanner(system.in);
  string line = null;
  listenserverreply(dis);
  while((line = scanner.nextline()) != null){//读取从键盘输入的一行
  dos.writeutf(line);//发给服务端
  system.out.println("client send msg : " + line);
  }
 } catch (exception e) {
  e.printstacktrace();
 }
 }
 
 //监听服务端回复的消息
 public void listenserverreply(final datainputstream dis){
 new thread(){
  @override
  public void run() {
  super.run();
  string line = null;
  try {
   while((line = dis.readutf()) != null){
   system.out.println("client receive msg from server: " + line);
   }
  } catch (ioexception e) {
   e.printstacktrace();
  }
  }
 }.start();
 }
 
}

先启动服务端,再启动客户端,在客户端的控制台输入消息并回车,就可以发送消息给客户端了,客户端收到消息后,马上会回复一个消息

以上就是本文的全部内容,希望对大家的学习有所帮助,也希望大家多多支持。