Java Socket C/S聊天 基于Java的Socket编写的C/S聊天程序实现
进阶的JFarmer 人气:0一个很久以前写的能够支持C/S模式聊天的Demo,利用Java的Socket写的。
只能聊一句就下线,挺low的。
服务器端程序Server
import java.io.BufferedReader; import java.io.IOException; import java.io.InputStreamReader; import java.net.ServerSocket; import java.net.Socket; public class TestTcpServer { public static void main(String[] args) { ServerSocket ss = null; BufferedReader in = null; try { ss = new ServerSocket(8888); System.out.println("服务器启动"); Socket socket = ss.accept(); System.out.println("连接建立"); System.out.println(socket.getInetAddress().getHostAddress()); //服务器接收客户端发送的数据 in = new BufferedReader(new InputStreamReader(socket.getInputStream())); String clientContent = in.readLine(); System.out.println("接收客户端消息: " +clientContent); } catch (IOException e) { e.printStackTrace(); } } }
客户端程序Clinet
import java.io.BufferedWriter; import java.io.IOException; import java.io.OutputStreamWriter; import java.net.Socket; import java.net.UnknownHostException; import java.util.Scanner; public class TestTcpClient { public static void main(String[] args) { Socket socket = null; BufferedWriter out = null; //客户端发送数据,服务器端接收 try { socket = new Socket("127.0.0.1",8888); System.out.println("与服务器连接了"); Scanner sc = new Scanner(System.in); String content = sc.nextLine(); out = new BufferedWriter((new OutputStreamWriter(socket.getOutputStream()))); out.write(content); out.flush(); sc.close(); } catch (UnknownHostException e) { e.printStackTrace(); } catch (IOException e) { e.printStackTrace(); } finally{ try { out.close(); socket.close(); } catch (IOException e) { e.printStackTrace(); } } } }
运行样例
注意要先起S端,否则:
好啦,先起S端:
然后S端就在等待,它“说话”也没人理它:
接着起C端:
S端也会有响应:
然后C端发消息:
S端收到消息,就双双Over了:
加载全部内容