The TCP:
the TCP protocol based on the request - response pattern
using transmission data stream implementation io
Create a server
1, specify the port to use to create a ServerSocket server
2, blocking wait for a connection accept, there is a accept to set up a client
3, Operation: io stream
4, free up resources
public class tcp {
public static void main(String[]args) throws IOException
{
System.out.println("-----Server-----");
// 1、指定端口 使用ServerSocket创建服务器
ServerSocket server=new ServerSocket(8888);
// 2、阻塞式等待连接accept
Socket client=server.accept();//返回一个Socket对象
System.out.println("一个客户端建立了连接");
// 3、操作:io流
DataInputStream dis=new DataInputStream(client.getInputStream());//输入
String data=dis.readUTF();
System.out.println(data);
// 4、释放资源
dis.close();
client.close();
server.close();
}
}
Create a client
1, to establish a connection: Socket created using the address and port of the client service +
2: Enter the output stream operation
3, the release of resources
public class tcp2 {
public static void main(String[]args) throws IOException
{
System.out.println("--------Client---------");
//1、建立连接:使用Socket创建客户端+服务的地址和端口
Socket client2=new Socket("localhost",8888);
//2、操作:输入输出流操作
DataOutputStream dos=new DataOutputStream(client2.getOutputStream());//输出
String data="杜雨龙最帅";
dos.writeUTF(data);
dos.flush();
//3、释放资源
dos.close();
client2.close();
}
}