重庆分公司,新征程启航
为企业提供网站建设、域名注册、服务器等服务
本文实例为大家分享了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(); } } } }