//Demonstrate Datagrams.
import java.net.*;
class WriteServer{
public static int serverPort = 666 ;
public static int clientPort = 999 ;
public static int buffer_size = 1024 ;
public static DatagramSocket ds ;
public static byte buffer[] = new byte[buffer_size];
public static void TheServer() throws Exception{
int pos = 0;
while(true){
int c = System.in.read();
switch(c){
case -1:
System.out.println("Server Quits.");
return;
case '\r':
break;
case '\n':
ds.send(new DatagramPacket(buffer,pos,InetAddress.getLocalHost(),clientPort));
pos = 0;
break;
default:
buffer[pos++] = (byte)c;
}
}
}
public static void TheClient() throws Exception{
while(true){
DatagramPacket p = new DatagramPacket (buffer,buffer.length);
ds.receive(p);
System.out.println(new String(p.getData(),0,p.getLength()));
}
}
public static void main(String[] args) throws Exception{
if(args.length == 1){
ds = new DatagramSocket(serverPort);
TheServer();
}else{
ds = new DatagramSocket(clientPort);
TheClient();
}
}
}
本文提供了一个使用Java实现的简单UDP服务器与客户端交互的例子。该程序演示了如何通过UDP协议进行基本的数据发送与接收。服务器接收来自标准输入的数据,并将其发送到客户端;客户端则接收并打印从服务器发来的消息。
1万+

被折叠的 条评论
为什么被折叠?



