网络通信的三要素
- IP地址
- 端口号
- 网络通信协议
TCP
客户端
import java.io.OutputStream;
import java.net.InetAddress;
import java.net.Socket;
public class TcpClient {
public static void main(String[] args) throws Exception {
InetAddress inetAddress = InetAddress.getByName("localhost");
Socket socket = new Socket(inetAddress, 9999);
OutputStream outputStream = socket.getOutputStream();
outputStream.write("你好".getBytes());
outputStream.close();
socket.close();
}
}
服务端
import java.io.ByteArrayOutputStream;
import java.io.InputStream;
import java.net.ServerSocket;
import java.net.Socket;
public class TcpServer {
public static void main(String[] args) throws Exception {
ServerSocket serverSocket = new ServerSocket(9999);
Socket socket = serverSocket.accept();
InputStream inputStream = socket.getInputStream();
ByteArrayOutputStream byteArrayOutputStream = new ByteArrayOutputStream();
byte[] buffer = new byte[1024];
int len;
while ((len = inputStream.read(buffer)) != -1)
byteArrayOutputStream.write(buffer, 0, len);
System.out.println(byteArrayOutputStream);
byteArrayOutputStream.close();
inputStream.close();
socket.close();
serverSocket.close();
}
}
先启动服务端,再启动客户端,之后可以看到服务端收到了客户端发的信息
UDP
发送端
import java.net.DatagramPacket;
import java.net.DatagramSocket;
import java.net.InetAddress;
public class UdpSender {
public static void main(String[] args) throws Exception {
DatagramSocket datagramSocket = new DatagramSocket();
InetAddress inetAddress = InetAddress.getByName("localhost");
DatagramPacket datagramPacket = new DatagramPacket(
"你好".getBytes(),
0,
"你好".getBytes().length,
inetAddress,
20000
);
datagramSocket.send(datagramPacket);
datagramSocket.close();
}
}
接收端
import java.net.DatagramPacket;
import java.net.DatagramSocket;
public class UdpReceiver {
public static void main(String[] args) throws Exception {
DatagramSocket socket = new DatagramSocket(20000);
byte[] buffer = new byte[1024];
DatagramPacket packet = new DatagramPacket(buffer, 0 , buffer.length);
socket.receive(packet);
System.out.println(new String(packet.getData(), 0, packet.getLength()));
}
}
先启动接收端,再启动发送端
|