2013-03-24 105 views
0

我是Java编程的新手,我试图创建一个UDP服务器。当我编译代码时,它说它不能监听端口4722,我想知道为什么。以下是代码。我会很感激任何建议。Java UDP服务器

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


public class Server 
{ 
public static void main(String[] args) throws IOException 
{ 
    DatagramSocket serverSocket = new DatagramSocket(4722); 
    Socket clientSocket = null; 
    byte[] receiveData = new byte[1024]; 
    byte[] sendData = new byte [1024];  

    boolean command = true; 
     try 
     { 
      serverSocket = new DatagramSocket(4722); 
      DatagramPacket receivePacket = new DatagramPacket(receiveData,receiveData.length); 
      System.out.println("Waiting for client..."); 


     } 


     catch (IOException e) 
     { 
      System.err.println("Could not listen on port: 4722."); 
      System.exit(1); 

     } 
     DatagramPacket packet = new DatagramPacket (sendData,sendData.length,4722); 
     serverSocket.send(packet); 



     PrintWriter out = new PrintWriter(clientSocket.getOutputStream(), true); 
     BufferedReader in = new BufferedReader(new InputStreamReader(clientSocket.getInputStream())); 
     String inputLine, outputLine; 
     mathematicalProtocol bbm = new mathematicalProtocol(); 

     outputLine = bbm.processInput(null); 
     out.println(outputLine); 

     while ((inputLine = in.readLine()) != null) 
     { 
      if(inputLine.equals("Bye.")) 
      break; 
      outputLine = bbm.processInput(inputLine); 
      out.println(outputLine); 
      if (outputLine.equals("Bye.")) 

      break; 
     } 

     out.close(); 
     in.close(); 
     clientSocket.close(); 
     serverSocket.close(); 
} 
} 
+1

您应该打印异常堆栈跟踪,而不是假设它会是。很有可能你有一个已经绑定到指定端口的进程。 – Perception 2013-03-24 10:51:53

回答

2

要初始化serverSocket,然后再犯同样的端口上的新DatagramSocket(你不能这样做,因为它已经绑定在第一DatagramSocket)。即删除以下行:

 serverSocket = new DatagramSocket(4722); 
+0

很好的抓Pescis。 – 2013-03-24 12:17:27

0

这是客户端/服务器UDP通信的完整示例。

服务器从文件中读取数据并将每行发送到客户端。

import java.io.BufferedReader; 
import java.io.FileReader; 
import java.io.IOException; 
import java.net.DatagramPacket; 
import java.net.DatagramSocket; 
import java.net.InetAddress; 
import java.net.SocketException; 

/** 
* @author nono 
* 
*/ 

public class UDPFileSender { 

static class Client implements Runnable { 

    // Reception socket 
    private DatagramSocket socket; 
    // UDP packet to receive data into 
    private DatagramPacket packet; 
    // Flag for initialisation 
    private boolean failedInit = true; 

    /** 
    * Client constructor. 
    * @param receptionPort 
    * @param packetMaxLenght 
    */ 
    public Client(int receptionPort, int packetMaxLenght) { 
     try { 
      // Create the socket using the reception port 
      this.socket = new DatagramSocket(receptionPort); 
      // Init the packet 
      this.packet = new DatagramPacket(new byte[packetMaxLenght],packetMaxLenght); 
      this.failedInit = false; 
     } catch (SocketException e) { 
      //Port already used or other error 
      e.printStackTrace(); 
     } 
    } 

    @Override 
    public void run() { 
     if(failedInit){ 
      return; 
     } 
     // Loop undefinitly 
     while(true){ 
      try { 

       System.out.println("Waiting for packet..."); 

       // Wait for packet 
       socket.receive(packet); 

       // Assuming you are receiving string 
       String msg = new String(packet.getData()); 
       System.out.println("Received : " + msg); 

      } catch (IOException e) { 
       e.printStackTrace(); 
      } 
     } 
    } 

} 

public static void main(String[] args) { 

    try { 

     int port = 4722; 

     //Start a client that can listen 
     new Thread(new Client(port,1024)).start(); 

     // Creaete a reader 
     BufferedReader reader = new BufferedReader(new FileReader("File.txt")); 

     //Create a socket 
     DatagramSocket socket = new DatagramSocket(); 

     // Create a packet 
     byte[] data = new byte[1024]; // Max length 
     DatagramPacket packet = new DatagramPacket(data, data.length); 

     // Set the destination host and port 
     packet.setAddress(InetAddress.getByName("localhost")); 
     packet.setPort(port); 

     String line = null; 
     while((line = reader.readLine()) != null){ 
      //Set the data 
      packet.setData(line.getBytes()); 

      //Send the packet using the socket 
      System.out.println("Sending : " + line); 
      socket.send(packet); 
      Thread.sleep(200); 
     } 

     //Close socket and file 
     reader.close(); 
     socket.close(); 

    } catch (IOException | InterruptedException e) { 
     e.printStackTrace(); 
    } 
} 

} 

如果文件包含:

Hello 
World 

你应该看到:

Waiting for packet... 
Sending : Hello 
Received : HelloWaiting for packet... 
Sending : World 
Received : World 
Waiting for packet...