Socket 使用TCP协议实现网络通信的Socket相关的类
如下新建了一个服务端和一个客户端,在对应的编辑器里面运行,既可以获得结果
import java.io.*;
import java.net.ServerSocket;
import java.net.Socket;
public class Server {
public static void main(String args[]) {
try {
//创建一个ServerSocket监听8080端口
ServerSocket server = new ServerSocket(8080);
// 等待请求
Socket socket = server.accept();
//接受到请求后使用socket进行通信。创建BufferedReader用于读取数据
BufferedReader is = new BufferedReader(new InputStreamReader(socket.getInputStream()));
String line = is.readLine();
System.out.println("received from client: " + line);
//创建PrintWriter,用于发送数据
PrintWriter pw = new PrintWriter(socket.getOutputStream());
pw.println("received data : " + line);
pw.flush();
//关闭资源
pw.close();
is.close();
socket.close();
server.close();
} catch (Exception e) {
e.printStackTrace();
}
}
}
import java.io.*;
import java.net.Socket;
public class Client {
public static void main(String args[]) {
String msg = "Client Data";
try {
//创建一个Socket,和本机的8080端口连接
Socket socket = new Socket("127.0.0.1",8080);
// 使用Socket创建PrintWriter和BufferedReader进行读写数据
PrintWriter pw = new PrintWriter(socket.getOutputStream());
BufferedReader is = new BufferedReader(new InputStreamReader(socket.getInputStream()));
//发送数据
pw.println(msg);
pw.flush();
//接受数据
String line = is.readline();
System.out.println("received from server: " + line);
//关闭资源
pw.close();
is.close();
socket.close();
} catch (Exception e) {
e.printStackTrace();
}
}
}