java udp协议源码_JAVA使用UDP协议的两人聊天室源码
时间: 2023-10-19 13:05:12 浏览: 98
以下是一个简单的Java UDP协议的两人聊天室源码,可以作为参考:
```java
import java.net.*;
public class UDPServer {
public static void main(String args[]) throws Exception {
DatagramSocket serverSocket = new DatagramSocket(9876);
byte[] receiveData = new byte[1024];
byte[] sendData = new byte[1024];
while (true) {
DatagramPacket receivePacket = new DatagramPacket(receiveData, receiveData.length);
serverSocket.receive(receivePacket);
String sentence = new String(receivePacket.getData());
InetAddress IPAddress = receivePacket.getAddress();
int port = receivePacket.getPort();
System.out.println("From " + IPAddress + ":" + port + " Message: " + sentence);
String capitalizedSentence = sentence.toUpperCase();
sendData = capitalizedSentence.getBytes();
DatagramPacket sendPacket = new DatagramPacket(sendData, sendData.length, IPAddress, port);
serverSocket.send(sendPacket);
}
}
}
```
```java
import java.net.*;
public class UDPClient {
public static void main(String args[]) throws Exception {
DatagramSocket clientSocket = new DatagramSocket();
InetAddress IPAddress = InetAddress.getByName("localhost");
byte[] sendData = new byte[1024];
byte[] receiveData = new byte[1024];
while (true) {
String sentence = new String(System.in.readAllBytes());
sendData = sentence.getBytes();
DatagramPacket sendPacket = new DatagramPacket(sendData, sendData.length, IPAddress, 9876);
clientSocket.send(sendPacket);
DatagramPacket receivePacket = new DatagramPacket(receiveData, receiveData.length);
clientSocket.receive(receivePacket);
String modifiedSentence = new String(receivePacket.getData());
System.out.println("From Server: " + modifiedSentence);
}
}
}
```
这是一个简单的聊天室,客户端可以输入消息并通过UDP协议发送给服务器,服务器将消息转换为大写后发送回客户端。你可以根据自己的需求修改代码。
阅读全文