概要:看过我之前文章的人都知道,client和server之间的通信必不可少的就是socket。而java已经帮我们做了很多事情。
这个从名字上就可以看出来,服务器上的socket? ?0.0
ServerSocket serverSocket = new ServerSocket(8888);
Socket socket = serverSocket.accept();
BufferedReader in = new BufferedReader(new InputStreamReader(socket.getInputStream()));
PrintWriter out = new PrintWriter(socket.getOutputStream(), true);
String message;
while ((message = in.readLine()) != null) {
System.out.println("收到客户端消息:" + message);
out.println("服务器已收到消息:" + message);
}
in.close();
out.close();
socket.close();
serverSocket.close();
Socket socket = new Socket("localhost", 8888);
BufferedReader in = new BufferedReader(new InputStreamReader(socket.getInputStream()));
PrintWriter out = new PrintWriter(socket.getOutputStream(), true);
BufferedReader keyboard = new BufferedReader(new InputStreamReader(System.in));
String message;
while (true) {
System.out.print("请输入要发送的消息:");
message = keyboard.readLine();
out.println(message);
String response = in.readLine();
System.out.println("收到服务器回复:" + response);
}
由于我这里写了while(true)已经写死了,就不用关闭了,因为也抵达不到那里去。
package org.cyl.database.net;
import java.io.*;
import java.net.*;
public class Client {
public static void main(String[] args) throws IOException {
Socket socket = new Socket("localhost", 8888);
System.out.println("已连接到服务器");
BufferedReader in = new BufferedReader(new InputStreamReader(socket.getInputStream()));
PrintWriter out = new PrintWriter(socket.getOutputStream(), true);
BufferedReader keyboard = new BufferedReader(new InputStreamReader(System.in));
String message;
while (true) {
System.out.print("请输入要发送的消息:");
message = keyboard.readLine();
out.println(message);
String response = in.readLine();
System.out.println("收到服务器回复:" + response);
}
}
}
package org.cyl.database.net;
import java.io.*;
import java.net.*;
public class Server {
public static void main(String[] args) throws IOException {
ServerSocket serverSocket = new ServerSocket(8888);
System.out.println("服务器已启动,等待客户端连接...");
Socket socket = serverSocket.accept();
System.out.println("客户端已连接,IP地址为:" + socket.getInetAddress().getHostAddress());
BufferedReader in = new BufferedReader(new InputStreamReader(socket.getInputStream()));
PrintWriter out = new PrintWriter(socket.getOutputStream(), true);
String message;
while ((message = in.readLine()) != null) {
System.out.println("收到客户端消息:" + message);
out.println("服务器已收到消息:" + message);
}
in.close();
out.close();
socket.close();
serverSocket.close();
}
}
结果图: