当前位置: 移动技术网 > IT编程>开发语言>Java > java学习之利用TCP实现的简单聊天示例代码

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

2019年07月19日  | 移动技术网IT编程  | 我要评论

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();
  }
 }
 }
}

总结

以上就是这篇文章的全部内容了,希望本文的内容对大家的学习或者工作具有一定的参考学习价值,如果有疑问大家可以留言交流,谢谢大家对移动技术网的支持。

如对本文有疑问, 点击进行留言回复!!

相关文章:

验证码:
移动技术网