对等2对等UDP套接字?
我尝试使用UDP套接字建立点对点网络,但我无法设法让两个节点相互通信。 看起来,作为客户端的节点由于某种原因无法连接到作为服务器的节点。
public class PeerNode {
DatagramSocket clientSocket;
public void sendRequest(String sentence, String host, int port) throws UnknownHostException, IOException{
clientSocket = new DatagramSocket (port);
InetAddress IPAddress = InetAddress.getByName(host);
byte[] sendData = new byte[1024];
System.out.println(sentence);
sendData = sentence.getBytes();
DatagramPacket sendPacket = new DatagramPacket(sendData, sendData.length, IPAddress, port);
clientSocket.send(sendPacket);
}
void mainLoop() throws IOException{
try {
// Establish the listen socket.
DatagramSocket serverSocket = new DatagramSocket(9876);
byte[] receiveData = new byte[1024];
System.out.println("listening on port " + serverSocket.getLocalPort());
//int count =0;
while (true) {
DatagramPacket receivePacket = new DatagramPacket(receiveData, receiveData.length);
serverSocket.receive(receivePacket);
String sentence = new String( receivePacket.getData());
System.out.println("Server: "+sentence);
RequestHandler request =new RequestHandler
// Create a new thread to process the request.
Thread thread = new Thread(request);
// Start the thread.
thread.start();
//count++;
}
} catch (Exception e) {
e.printStackTrace();
}
}
}
public class RequestHandler implements Runnable{
DatagramPacket packet;
DatagramSocket socket;
byte[] sendData = new byte[1024];
public RequestHandler(DatagramPacket packet,DatagramSocket socket) throws Exception
{
this.packet = packet;
this.socket = socket;
String sentence = new String(packet.getData());
System.out.println("handler : "+sentence);
}
@Override
public void run()
{
try {
System.out.println("Test");
processRequest();
} catch (Exception e) {
System.out.println(e);
}
}
/*
* Gets a request from a node.
*/
private void processRequest() throws Exception
{
String sentence = new String( packet.getData());
System.out.println("RECEIVED: " + sentence);
InetAddress IPAddress =packet.getAddress();
int port = packet.getPort();
String capitalizedSentence = sentence.toUpperCase();
sendData = capitalizedSentence.getBytes();
DatagramPacket sendPacket =new DatagramPacket(sendData, sendData.length, IPAddress, port);
socket.send(sendPacket);
socket.close();
}
}
public class ClientServer {
public static void main( String [] args ) throws IOException{
PeerNode node1=new PeerNode();
PeerNode node2=new PeerNode();
node1.sendRequest("Hellllll", "localhost",9876);
node2.mainLoop();
}
}
链接地址: http://www.djcxy.com/p/35095.html
下一篇: Java: Invalid keystore format, when generated through code
