介绍
本篇文章给大家分享的是有关怎么在Java中使用TCP实现一个在线聊天功能,小编觉得挺实用的,因此分享给大家学习,希望大家阅读完这篇文章后可以有所收获,话不多说,跟着小编一起来看看吧。
客户端的代码:
package tcp.http; import . io . *; import java.net。*; import java.util.Scanner; public class 客户{ public static  void main (String [], args), throws IOException { Scanner 扫描仪=new 扫描仪(系统);//1 .创建插座 Socket tcpClientSocket=new 插座();//2. tcp要发送消息,必须先建立连接 byte [], IPv4={127, 0, 0, 1},,,//连接到本机 InetAddress serverAddress=InetAddress.getByAddress (IPv4); SocketAddress serverSocketAddress=new InetSocketAddress (serverAddress, 7777); tcpClientSocket.connect (serverSocketAddress);//连接上了,(连接过程代码比较长,但是没有什么复杂的,只需要查文档根据函数的构造过程,一步步来写就好了) 而(真正的){,//写个死循环来聊天 String 请求=scanner.nextLine ();//通过字节流写入请求 OutputStream 操作系统=tcpClientSocket.getOutputStream ();//通过打印流打印和写入=new  PrintStream ; PrintStream(操作系统,真的,“UTF-8"); out.println(请求);//通过字节流读取响应 InputStream 是=tcpClientSocket.getInputStream (); BufferedReader 读者=new BufferedReader (new InputStreamReader(是,“UTF-8")),,//通过readLine()来保证每次都能把一句完整的话读完(\ r \ n是标志); String 反应=reader.readLine (); System.out.println(,,,,,,,, +反应); }//tcpClientSocket.close (); } }
服务器端的代码:
package tcp.threads; import . io . *; import java.net。*; import java.util.Scanner; import java . util . concurrent . *; public class 服务器{ private static  class TalkRunnable  implements Runnable{,//一个个的工作线程 private Socket  clientSocket; TalkRunnable (Socket 插座){ this.clientSocket=套接字; } @Override public void  run () { 尝试{ InetAddress clientAddress=clientSocket.getInetAddress (); int clientPort=clientSocket.getPort (); System.out.printf (“ID为,% s: % d 的好友上线了% n", clientAddress.getHostAddress (), clientPort);//获取字节流 InputStream =零; 是=clientSocket.getInputStream ();//字节流转换为字符流 InputStreamReader isReader=零; isReader=new InputStreamReader(是,“UTF-8");//获取输出字节流 OutputStream 操作系统=clientSocket.getOutputStream ();//获取打印流=new  PrintStream ; PrintStream(操作系统,真的,“UTF-8");//获取缓冲字符流 BufferedReader 读者=new BufferedReader (isReader); 而(真正的){,//死循环聊天 String 行=reader.readLine (); System.out.println(,,,,,,,好友说:“+线); Scanner 扫描仪=new 扫描仪(系统); String 反应=scanner.nextLine (); out.println(响应); } }捕捉(IOException e) { e.printStackTrace (); } } } public static  void main (String [], args), throws IOException {//监听连接 ServerSocket tcpServerSocket=new 考察(7777);//定义阻塞队列 BlockingQueue运行结果:
部内容,希望对大家的学习有所帮助,也希望大家多多支持。以上就是怎么在Java中使用TCP实现一个在线聊天功能,小编相信有部分知识点可能是我们日常工作会见到或用到的。希望你能通过这篇文章学到更多知识。更多详情敬请关注行业资讯频道。
怎么在Java中使用TCP实现一个在线聊天功能