TCP
TCP 在计网中的地位非常重要,很多协定的运行都是以 TCP 为根底来运行的,尽管 TCP 的开销比 UDP 开销大,但其实现的可靠性交付是一大特点,其还具备流量管制、拥塞管制等个性,在面试中也少不了谈其三次握手、四次挥手以及其余问题。
public class LengthCalculator extends Thread{
private Socket socket;
public LengthCalculator(Socket socket){this.socket=socket;}
@Override
public void run(){
try{OutputStream os =socket.getOutputStream();
InputStream is =socket.getInputStream();
int ch=0;
byte[] buff =new byte[1024];
ch=is.read(buff);
String content =new String(buff,0,ch);
System.out.println(content);
os.write(String.valueOf(content.length()).getBytes());
is.close();
os.close();
socket.close();} catch (IOException e) {e.printStackTrace();
}
}
}
public class TCPClient {public static void main(String[] args) throws IOException {Socket socket=new Socket("127.0.0.1",65000);
OutputStream out = socket.getOutputStream();
InputStream in = socket.getInputStream();
out.write("Hello World!".getBytes());
int ch=0;
byte[] bytes=new byte[1024];
ch=in.read(bytes);
String content=new String(bytes,0,ch);
System.out.println("接管到内容 content:"+content);
in.close();
out.close();
socket.close();}
}
public class TCPServer {public static void main(String[] args) throws IOException {ServerSocket ss =new ServerSocket(65000);
while(true){Socket socket=ss.accept();
new LengthCalculator(socket).start();}
}
}
UDP
UDP 是数据报传输协定,其可传输的大小取决于数据报的大小,不像 TCP 协定一样受到 MTU 最大传输的限度,也不必像 TCP 一样实现报文切片等个性进行传输,但 UDP 的次要传输速率取决于单方的带宽,且不提供可靠性交付。
public class UDPClient {public static void main(String[] args) throws IOException {DatagramSocket socket =new DatagramSocket();
byte[] buf ="hello world".getBytes();
// 将 IP 封装为 InetAddress 对象
InetAddress address =InetAddress.getByName("127.0.0.1");
// 将要发送数据封装成 DatagramPacket 对象,填写上 ip 地址与端口号
DatagramPacket packet =new DatagramPacket(buf,buf.length,address,65001);
socket.send(packet);
byte[] data =new byte[100];
// 创立 DatagramPacket 对象来存储服务端发送的数据
DatagramPacket receivedPacket = new DatagramPacket(data,data.length);
socket.receive(receivedPacket);
// 将数据取出来并打印
String content = new String(receivedPacket.getData(),0,receivedPacket.getLength());
System.out.println(content);
}
}
public class UDPServer {public static void main(String[] args) throws IOException {
// 服务端接管客户端发送的数据报
DatagramSocket socket =new DatagramSocket(65001);
// 存储从客户端收到的内容
byte[] buff =new byte[100];
// 接管客户端发送的内容,并将内容封装进 DatagramPacket 对象中
DatagramPacket packet =new DatagramPacket(buff,buff.length);
socket.receive(packet);
// 从 DatagramPacket 中获取真正存储的数据
byte[] data =packet.getData();
// 将数据从二进制转化为字符串模式
String content =new String(data,0,packet.getLength());
System.out.println(content);
// 将要发送给客户端的数据换成二进制
byte[] sendedContent =String.valueOf(content.length()).getBytes();
// 服务端给客户端发送数据报
// 从 DatagramPacket 对象中获取到数据的起源地址与端口号
DatagramPacket packetToClient =new DatagramPacket(sendedContent,sendedContent.length,packet.getAddress(),packet.getPort());
socket.send(packetToClient);
}
}