?
客户端
四个基本步骤:
1.创建Socket
2.打开 连接到Socket的 输入流/出流:
3.按照协议对Socket进行 读/写 操纵
4.关闭Socket:
服务器端
四个基本步骤:
1.调用ServerSocket(int prot):
2.调用accept():
3.调用该Socket类对象的getOutputStream和getInputStream():
4.关闭ServerSocket和Socket对象:
练习代码如下:
@Test
public void client() throws IOException {
//1. creat Socket
Socket socket = new Socket("127.0.0.1",8868);
//2. get ops from Socket
OutputStream ops = socket.getOutputStream();
//3. reading or writing by protocol
ops.write("有趣".getBytes(StandardCharsets.UTF_8));
//4. close Socket
socket.close();
}
@Test
public void server() throws IOException {
//1.creat ServerSocket
ServerSocket serverSocket = new ServerSocket(8868);
//2.creat Socket by method of ServerSocket
Socket socket = serverSocket.accept();
//3.reading or writing
InputStream inputStream = socket.getInputStream();
int len;
ByteArrayOutputStream bais = new ByteArrayOutputStream();
while ((len = inputStream.read()) != -1){
bais.write(len);
}
System.out.println(bais.toString());
//4.close
serverSocket.close();
socket.close();
}
|