初识socket
TCP 服务端:
```java
public class SocketService {
public static void main(String[] args) throws IOException {
//1 创建socket,指定监听端口
ServerSocket serverSocket = new ServerSocket(9999);
System.out.println("------创建socket,指定监听端口----");
//2 当客户端没有链接9999端口时,程序阻塞,等待连接
Socket accept = serverSocket.accept();
System.out.println("------有客户端请求----");
InputStream inputStream = accept.getInputStream();
byte[] buf = new byte[1024];
int readLen = 0;
while ((readLen=inputStream.read(buf))!=-1){
System.out.println(new String(buf,0,readLen));
}
inputStream.close();
accept.close();
}
}
TCP客户端
public static void main(String[] args) throws Exception {
Socket socket = new Socket(InetAddress.getLocalHost(), 9999);
System.out.println("-------链接成功------");
OutputStream outputStream = socket.getOutputStream();
outputStream.write("-----:你好socket,我是第一个客户端".getBytes());
outputStream.close();
socket.close();
}
好了,简单的客户端服务端交互已经完成,先启动服务端,在启动客户端
UDP 接收端
public class UDPSocket2 {
public static void main(String[] args) throws IOException {
DatagramSocket socket = new DatagramSocket(9999);
byte[] bytes = new byte[1024];
DatagramPacket packet = new DatagramPacket(bytes, bytes.length);
socket.receive(packet);
int length = packet.getLength();
byte[] data = packet.getData();
String s = new String(data, 0, length);
System.out.println("----UDPSocket2---接收到数据:"+s);
String str = "你好 UDP 1";
DatagramPacket packetSend = new DatagramPacket(str.getBytes(), str.getBytes().length, InetAddress.getLocalHost(),9998);
socket.send(packetSend);
socket.close();
}
UDP发送端
public class UDPSocket1 {
public static void main(String[] args) throws IOException {
DatagramSocket socket = new DatagramSocket(9998);
String str = "你好 UDP 2";
byte[] bytes = str.getBytes();
DatagramPacket packet = new DatagramPacket(bytes,bytes.length, InetAddress.getLocalHost(),9999);
socket.send(packet);
byte[] bytesReceive = new byte[1024];
DatagramPacket packetReceive = new DatagramPacket(bytes, bytes.length);
socket.receive(packetReceive);
int length = packet.getLength();
byte[] data = packet.getData();
String s = new String(data, 0, length);
System.out.println("----UDPSocket1---接收到数据:"+s);
socket.close();
}
}
TCP/UDP区别和优缺点
|