话不多说,直接上代码和运行结果。
服务端代码:
public static void main(String[] args) {
final int PORT = 8899;
ServerSocket serverSocket = null;
BufferedWriter writer = null;
try {
serverSocket = new ServerSocket(PORT);
System.out.println("服务器已启动!正在监听端口"+PORT);
while (true){
Socket socket = serverSocket.accept();
System.out.println("客户端 "+socket.getPort()+" 已连接");
BufferedReader reader = new BufferedReader(new InputStreamReader(socket.getInputStream()));
writer = new BufferedWriter(new OutputStreamWriter(socket.getOutputStream()));
String message = reader.readLine();
if (message != null){
System.out.println("收到一条来自客户端 "+socket.getPort()+" 发送的消息:"+message);
}
//加了\n readLine才能生效
writer.write("你才是" + message + "\n");
writer.flush(); //清理缓冲区
}
} catch (IOException e) {
e.printStackTrace();
} finally {
if(writer != null){
try {
writer.close();
System.out.println("服务器挂掉了。。再见");
} catch (IOException e) {
e.printStackTrace();
}
}
}
}
客户端代码:
public static void main(String[] args) {
final String Host = "127.0.0.1";
final int Port = 8899;
BufferedWriter writer = null;
try {
Socket socket = new Socket(Host,Port);
BufferedReader reader = new BufferedReader(new InputStreamReader(socket.getInputStream()));
writer = new BufferedWriter(new OutputStreamWriter(socket.getOutputStream()));
BufferedReader console = new BufferedReader(new InputStreamReader(System.in));
String message = console.readLine();
writer.write(message+"\n");
writer.flush();
String responseMsg = reader.readLine();
System.out.println("收到了来自服务器的回复:" + responseMsg);
} catch (IOException e) {
e.printStackTrace();
} finally {
if(writer != null){
try {
writer.close();
System.out.println("客户端关闭了连接");
} catch (IOException e) {
e.printStackTrace();
}
}
}
}
先运行Server代码,此时服务成功启动!:
再运行客户端代码,此时服务端和客户端连接成功!:
在客户端发送消息:
这个教程是一个多线程的版本,其实就是把服务端的代码中可以复用的部分抽出来单独作为一个内部类,继承Thread,然后在while循环里,每当有一个客户端前来访问,都将开启一个线程专门来处理这个客户端的请求
实际上,上面的极简版本代码,完全也可以多复制几个Client, 然后同时运行,Server端代码会一个个的按照顺序收到客户端的请求并返回对应的结果,while循环永不疲倦,除非断电。
免责声明:本站发布的内容(图片、视频和文字)以原创、转载和分享为主,文章观点不代表本网站立场,如果涉及侵权请联系站长邮箱:is@yisu.com进行举报,并提供相关证据,一经查实,将立刻删除涉嫌侵权内容。