概述
- Client/Server结构:客户端和服务器结构
- TCP
传输控制协议(Transmission Control Protocol)
可靠的连接 - UDP
用户数据报协议(User Datagram Protocol)
发送端发出数据时,不会确认接收端是否存在;接收端接收数据时,不会向发送端反馈是否收到
网络传输的基本单位 :数据报(Datagram)
TCP
服务端
import java.io.InputStream;
import java.net.ServerSocket;
import java.net.Socket;
public class Server {
public static void main(String[] args)throws Exception {
ServerSocket server = new ServerSocket(5000);
Socket socket = server.accept();
System.out.println("有客户端连进");
InputStream inputStream = socket.getInputStream();
byte[] bytes = new byte[1024];
StringBuilder stringBuilder = new StringBuilder();
int len;
while ((len = inputStream.read(bytes)) != -1) {
stringBuilder.append(new String(bytes, 0, len));
}
System.out.println("接收到客户端发送的消息:" + stringBuilder);
socket.close();
server.close();
}
}
- 1
- 2
- 3
- 4
- 5
- 6
- 7
- 8
- 9
- 10
- 11
- 12
- 13
- 14
- 15
- 16
- 17
- 18
- 19
- 20
- 21
- 22
- 23
- 24
- 25
- 26
- 27
- 28
- 29
- 30
- 31
客户端
import java.io.OutputStream;
import java.net.Socket;
public class Client {
public static void main(String[] args) throws Exception {
Socket socket = new Socket("localhost", 5000);
OutputStream out = socket.getOutputStream();
out.write("Python".getBytes());
socket.shutdownOutput();
socket.close();
}
}
- 1
- 2
- 3
- 4
- 5
- 6
- 7
- 8
- 9
- 10
- 11
- 12
- 13
- 14
- 15
- 16
- 17
接收端
import java.net.DatagramPacket;
import java.net.DatagramSocket;
public class Receiver {
public static void main(String[] args) throws Exception {
DatagramSocket ds = new DatagramSocket(5000);
byte[] bytes = new byte[1024 * 64];
DatagramPacket dp = new DatagramPacket(bytes, bytes.length);
ds.receive(dp);
String str = new String(bytes, 0, dp.getLength());
System.out.println(str);
}
}
- 1
- 2
- 3
- 4
- 5
- 6
- 7
- 8
- 9
- 10
- 11
- 12
- 13
- 14
- 15
- 16
- 17
- 18
- 19
- 20
发送端
import java.net.DatagramPacket;
import java.net.DatagramSocket;
import java.net.InetAddress;
public class Sender {
public static void main(String[] args) throws Exception {
DatagramSocket ds = new DatagramSocket();
byte[] bytes = "Python".getBytes();
DatagramPacket dp = new DatagramPacket(bytes, bytes.length, InetAddress.getByName("localhost"), 5000);
ds.send(dp);
ds.close();
}
}
- 1
- 2
- 3
- 4
- 5
- 6
- 7
- 8
- 9
- 10
- 11
- 12
- 13
- 14
- 15
- 16
- 17
- 18
- 19
- 20