概要:看过我之前文章的人都知道,client和server之间的通信必不可少的就是socket。而java已经帮我们做了很多事情。
创建Server端
第一步,创建ServerSocket
这个从名字上就可以看出来,服务器上的socket 0.0
ServerSocket serverSocket = new ServerSocket(8888);
第二步,就是接受客户端传来的socket
Socket socket = serverSocket.accept();
第三步,便是创建输入流和输出流
BufferedReader in = new BufferedReader(new InputStreamReader(socket.getInputStream()));
PrintWriter out = new PrintWriter(socket.getOutputStream(), true);
第四步,便是循环读取或者输出,dosomething
String message;
while ((message = in.readLine()) != null) {
System.out.println("收到客户端消息:" + message);
out.println("服务器已收到消息:" + message);
}
最后一定不要忘记了关闭这些
in.close();
out.close();
socket.close();
serverSocket.close();
创建Client端
第一步,创建Socket
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));
第三步,便是循环dosomething
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();
}
}
结果图: