一 各协议所处层次:
二 socket所处层次:
三 tcp编程流程图:
四 udp编程流程图:
五 Tcp传输数据:
TcpServer:
public class TcpServer {
public static void main(String[] args) throws IOException {
ServerSocket serverSocket = new ServerSocket(8081);
try {
System.out.println("Tcp服务端启动");
Socket accept = serverSocket.accept();
InputStream inputStream = accept.getInputStream();
byte[] bytes = new byte[1024];
int len = inputStream.read(bytes);
String result = new String(bytes, 0, len);
System.out.println("接收到客户端传来的数据:"+result);
accept.shutdownInput();
OutputStream outputStream = accept.getOutputStream();
String data = "服务器已接收到客户端发送的数据";
outputStream.write(data.getBytes());
outputStream.flush();
accept.shutdownOutput();
} finally {
serverSocket.close();
}
}
}
TcpClient:
public class TcpClient {
public static void main(String[] args) throws IOException {
Socket socket = new Socket("127.0.0.1", 8081);
try {
System.out.println("Tcp客户端启动");
OutputStream outputStream = socket.getOutputStream();
String data = "客户端发送的数据";
outputStream.write(data.getBytes());
outputStream.flush();
System.out.println("客户端发送数据完毕");
socket.shutdownOutput();
byte[] bytes = new byte[1024];
InputStream inputStream = socket.getInputStream();
int len = inputStream.read(bytes);
String result = new String(bytes,0,len);
System.out.println("服务器反馈:"+result);
socket.shutdownInput();
} finally {
socket.close();
}
}
}
六 Udp传输数据:
UdpServer:
public class UdpServer {
public static void main(String[] args) throws Exception {
DatagramSocket datagramSocket = new DatagramSocket(8081);
try {
System.out.println("Udp服务端启动");
byte[] bytes = new byte[1024];
DatagramPacket datagramPacket = new DatagramPacket(bytes,bytes.length);
datagramSocket.receive(datagramPacket);
String addresss = datagramPacket.getAddress().toString();
byte[] data = datagramPacket.getData();
int len = datagramPacket.getLength();
String result = new String(data, 0, len);
System.out.println("服务器从IP:"+addresss+"||接收到的数据:"+result);
} finally {
datagramSocket.close();
}
}
}
UdpClient:
public class UdpClient {
public static void main(String[] args) throws Exception {
DatagramSocket datagramSocket = new DatagramSocket();
try {
System.out.println("Udp客户端启动");
String data = "客户端发送的数据";
byte[] bytes = data.getBytes();
InetSocketAddress inetSocketAddress = new InetSocketAddress("127.0.0.1", 8081);
DatagramPacket datagramPacket = new DatagramPacket(bytes,bytes.length,inetSocketAddress);
datagramSocket.send(datagramPacket);
System.out.println("客户端发送完毕");
} finally {
datagramSocket.close();
}
}
}