import socket # 客户端的IP地址和端口号 client_ip = '192.168.1.1'client_port = 12345 # 服务器的IP地址和端口号 server_ip = '202.112.20.132'server_port = 54321 # 创建UDP套接字 client_socket = socket.socket(socket.AF_INET, socket.SOCK_DGRAM) # 绑定客户端的IP地址和端口号 client_socket.bind((client_ip, client_port)) # 发送数据 data = 'Hello, this is client.'client_socket.sendto(data.encode(), (server_ip, server_port)) # 接收数据 recv_data, addr = client_socket.recvfrom(1024)print('Received data: ', recv_data.decode()) # 关闭套接字 client_socket.close()将以上程序变为Java的socket程序
时间: 2024-03-04 14:49:16 浏览: 135
simple_tcp_client.zip_client_tcp
以下是将Python程序转化为Java程序的过程:
```
import java.io.*;
import java.net.*;
public class Client {
public static void main(String[] args) throws Exception {
String client_ip = "192.168.1.1";
int client_port = 12345;
String server_ip = "202.112.20.132";
int server_port = 54321;
// 创建UDP套接字
DatagramSocket client_socket = new DatagramSocket(client_port, InetAddress.getByName(client_ip));
// 发送数据
String data = "Hello, this is client.";
byte[] send_data = data.getBytes();
DatagramPacket send_packet = new DatagramPacket(send_data, send_data.length, InetAddress.getByName(server_ip), server_port);
client_socket.send(send_packet);
// 接收数据
byte[] recv_buffer = new byte[1024];
DatagramPacket recv_packet = new DatagramPacket(recv_buffer, recv_buffer.length);
client_socket.receive(recv_packet);
String recv_data = new String(recv_packet.getData(), 0, recv_packet.getLength());
System.out.println("Received data: " + recv_data);
// 关闭套接字
client_socket.close();
}
}
```
转化后的Java程序与原来的Python程序实现的功能相同,都是通过UDP协议向服务器发送"Hello, this is client."字符串,并从服务器接收数据。
阅读全文