网络编程问题:TCP/UDP Java通信实例
在Java中,我们可以使用Socket和DatagramSocket来实现TCP和UDP的通信。下面是一个简单的例子,展示如何通过TCP建立连接并发送数据:
import java.io.*;
import java.net.*;
public class TCPClient {
public static void main(String[] args) {
// 创建一个Socket对象
try (Socket socket = new Socket("localhost", 1234);
BufferedReader in = new BufferedReader(new InputStreamReader(socket.getInputStream())))) {
System.out.println("Connected to server!");
// 发送数据
String message = "Hello, Server!";
in.write(message.getBytes());
// 接收并打印服务器响应
String response = in.readLine();
System.out.println("Server Response: " + response);
} catch (IOException e) {
e.printStackTrace();
System.out.println("Error connecting to server.");
}
}
}
这个例子中,客户端创建了一个Socket连接到”localhost”的1234端口。然后它发送了一条消息,并接收和打印了服务器的响应。
注意:在实际生产环境中,应处理好异常,增加代码的健壮性。
还没有评论,来说两句吧...