TCP/IP
TCP/IP协议是一个协议的集合,分为四层:应用层,传输层,网络层,数据链路层。它和UDP的重要区别是有连接。
客户端
public class TestClient {public static void main(String[] args) throws IOException {
InetAddress address=InetAddress.getByName(“PC-C-29”);
int port=10000;
Socket socket=new Socket(address,port);OutputStream os=socket.getOutputStream(); String content="laobiao"; os.write(content.getBytes()); InputStream inputStream = socket.getInputStream(); byte[] b=new byte[1024*3]; int len = inputStream.read(b); String message=new String(b,0,len); System.out.println(message); socket.close();
}
}
2. 服务端
public class TestServer {
public static void main(String[] args) throws IOException {
ServerSocket ss=new ServerSocket(10000);
Socket accept=ss.accept();
InputStream is=accept.getInputStream();
byte[] b=new byte[1024*3];
int len = is.read(b);
String content=new String(b,0,len);
System.out.println("服务端收到来自客户端的消息:"+content);
OutputStream outputStream = accept.getOutputStream();
String message="客户端已收到";
outputStream.write(message.getBytes());
//ss.close();一般不关闭服务端
}
}