用java写Smart-Socket 实现 upd clent
时间: 2024-05-04 11:22:26 浏览: 237
Java-Socket编程
4星 · 用户满意度95%
Smart-Socket 是一个基于Java语言的网络编程库,可以用来实现UDP客户端。下面是一个简单的示例代码:
```java
import java.net.*;
public class UDPSocketClient {
public static void main(String[] args) throws Exception {
// 创建一个UDP Socket
DatagramSocket socket = new DatagramSocket();
// 发送数据
String message = "Hello, world!";
InetAddress address = InetAddress.getByName("127.0.0.1");
int port = 8888;
byte[] buffer = message.getBytes();
DatagramPacket packet = new DatagramPacket(buffer, buffer.length, address, port);
socket.send(packet);
// 接收数据
byte[] receiveBuffer = new byte[1024];
DatagramPacket receivePacket = new DatagramPacket(receiveBuffer, receiveBuffer.length);
socket.receive(receivePacket);
String receiveMessage = new String(receivePacket.getData(), 0, receivePacket.getLength());
System.out.println("Receive message: " + receiveMessage);
// 关闭Socket
socket.close();
}
}
```
这个示例程序使用 `DatagramSocket` 类创建了一个UDP Socket,并且发送了一个消息到指定的IP地址和端口号。然后等待接收服务器返回的消息,并打印出来。最后关闭Socket。
阅读全文