public class TCPTest {
@Test
public void serverTest() throws IOException {
//创建一个serverSocket
ServerSocket serverSocket = new ServerSocket(8989);
Socket socket = serverSocket.accept();//随时准备接收客户端请求
//以IO流发送给客户端信息
OutputStream out = socket.getOutputStream();
PrintWriter print = new PrintWriter(out);
print.write("来自服务端的问候...");
print.close();
out.close();
socket.close();
serverSocket.close();
}
@Test
public void clientTest() throws IOException {
InetAddress address = InetAddress.getByName("127.0.0.1");
Socket socket = new Socket(address, 8989);
InputStream in = socket.getInputStream();
BufferedReader reader = new BufferedReader(new InputStreamReader(in));
System.out.println("^-^" + reader.readLine());
in.close();
reader.close();
socket.close();
}
}
转载于:https://blog.51cto.com/nengge/1762778