一个很久以前写的能够支持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了:
到此这篇关于基于Java的Socket编写的C/S聊天程序实现的文章就介绍到这了,更多相关Java Socket C/S聊天内容请搜索自学编程网以前的文章或继续浏览下面的相关文章希望大家以后多多支持自学编程网!
- 本文固定链接: https://zxbcw.cn/post/182523/
- 转载请注明:必须在正文中标注并保留原文链接
- QQ群: PHP高手阵营官方总群(344148542)
- QQ群: Yii2.0开发(304864863)