日期:2014-05-20  浏览次数:20713 次

java 的udp服务器端代码
谁能给我一个java 的udp的服务器端的 代码?能够接收我的客户端的数据并转发出去给别人。
能够实现跨网段 更好

------解决方案--------------------
给你个简单的自己改造

Java code

import java.io.*;
import java.net.*;
import java.util.*;

public class UDPTimeServer
{
    
    private static byte[] buffer=new byte[1024];
    private static DatagramPacket inPacket,outPacket;
    private static DatagramSocket datagramSocket;
    private static String s;
    public UDPTimeServer(){UDPS();
                        }
        
        public static String UDPS()
    {
        System.out.println("开始!!");
        try
        {
            datagramSocket=new DatagramSocket(8000);
            while(true)
            {
                inPacket=new DatagramPacket(buffer,buffer.length);
                
                datagramSocket.receive(inPacket);
                
                InetAddress clientAddress=inPacket.getAddress();
                int clientPort=inPacket.getPort();
                
                s=new String(inPacket.getData(),0,inPacket.getLength());
                System.out.println("地址:"+clientAddress+"  端口:"+clientPort);
                System.out.println("收到数据:"+s);
                new Rtest().jTextArea1.append(s);
                //datagramSocket.close();
            }
        }catch(IOException e){e.printStackTrace();}
        
                return s;
    }
    
    public static void main(String args[])
    {
        new UDPTimeServer();
    }
}