一聚教程网:一个值得你收藏的教程网站

最新下载

热门教程

java学习之利用TCP实现的简单聊天示例代码

时间:2018-01-10 编辑:猪哥 来源:一聚教程网

TCP

TCP协议是面向连接、保证高可靠性(数据无丢失、数据无失序、数据无错误、数据无重复到达)传输层协议。

TCP通过三次握手建立连接,通讯完成时要拆除连接,由于TCP是面向连接的所以只能用于端到端的通讯。

本文主要介绍了java利用TCP实现简单聊天的相关内容,分享出来供大家参考学习,下面话不多说了,来一起看看详细的介绍吧。

示例代码

使用tcp协议实现的简单聊天功能(非常简单的)

思想:使用2个线程,一个线程是用来接收消息的,另一个线程是用来发消息的。

客户端Demo代码:

public class SendDemo {
 public static void main(String[] args) throws Exception{
 Socket socket= new Socket(InetAddress.getLocalHost(),8888);
 SendImpl sendImpl= new SendImpl(socket);
 //发送的线程
 new Thread(sendImpl).start();
 //接收的线程
 ReciveImpl reciveImpl=new ReciveImpl(socket);
 new Thread(reciveImpl).start();
 }
}

服务器端Demo代码:

public class ServerDemo {
 public static void main(String[] args) throws Exception {
 ServerSocket serverSocket =new ServerSocket(8888);
 Socket socket=serverSocket.accept();
 SendImpl sendImpl= new SendImpl(socket);
 new Thread(sendImpl).start();
 ReciveImpl reciveImpl=new ReciveImpl(socket);
 new Thread(reciveImpl).start();
 }
}

发送线程的Demo代码:

public class SendImpl implements Runnable{
 private Socket socket;
 public SendImpl(Socket socket) {
 this.socket=socket;
 // TODO Auto-generated constructor stub
 }
 @Override
 public void run() {
 Scanner scanner=new Scanner(System.in);
 while(true){
  try {
  OutputStream outputStream = socket.getOutputStream();
  String string= scanner.nextLine();
  outputStream.write(string.getBytes());
  } catch (IOException e) {
  // TODO Auto-generated catch block
  e.printStackTrace();
  }
 }
 }
}

接收线程的Demo代码:

public class ReciveImpl implements Runnable {
 private Socket socket;
 public ReciveImpl(Socket socket) {
 this.socket=socket;
 // TODO Auto-generated constructor stub
 }
 @Override
 public void run() {
 while(true ){
  try {
  InputStream inputStream = socket.getInputStream();
  byte[] b=new byte[1024];
  int len= inputStream.read(b);
  System.out.println("收到消息:"+new String(b,0,len));
  
  } catch (IOException e) {
  // TODO Auto-generated catch block
  e.printStackTrace();
  }
 }
 }
}

热门栏目