嗨,谢谢你,
我不认为我的问题与建议的问题重复。我知道nullpointer异常,但我不知道如何解决这个问题(假设root是一个nullpointer异常或不是)。
所以我正在尝试建立客户端与客户端的通信,我遇到了一些麻烦。
所以目前我有一个作为服务器的行为,另一个作为客户端(用于一个方向的消息),我正在努力让服务器以连接的形式向客户端发送连接确认一条简单的短信。
以下是我的代码。 我的代码目前使客户端向服务器发送一个简单的问候消息。注释掉的代码是我最近尝试将连接确认消息发送回客户端,但它没有用。
这是服务器代码:
try
{
//SeederPanel.setVisible(true);
//LeecherPanel.setVisible(false);
//waiting to be connected to
System.out.println("Seeder waiting for leecher..");
DatagramSocket SeederSocket = new DatagramSocket(2345);
byte[] SeederBuffer = new byte[512];
DatagramPacket DGP = new DatagramPacket(SeederBuffer,SeederBuffer.length);
//receiving connection attempt
String message = "";
SeederSocket.receive(DGP);
message = new String(SeederBuffer);
System.out.println(message);
/*
//Response to connection attempt
String returnGreeting = "You have successfully connected to the seeder!";
SeederBuffer = returnGreeting.getBytes();
DatagramPacket DGPResponse = new DatagramPacket(SeederBuffer,SeederBuffer.length);
SeederSocket.send(DGPResponse);
*/
if(message=="Hello from the leecher")
{
NotifyLeecherConnect();
}
}
catch (SocketException e)
{
e.printStackTrace();
}
catch (UnknownHostException e)
{
e.printStackTrace();
}
catch (IOException e)
{
e.printStackTrace();
}
这是客户端代码:
try
{
//attempting to connect
InetAddress MyAddress = InetAddress.getByName(txtHostAddress.getText());
DatagramSocket LeecherSocket = new DatagramSocket();
String Greeting = "Hello from the leecher";
byte[] LeecherBuffer = Greeting.getBytes();
DatagramPacket dp = new DatagramPacket(LeecherBuffer,LeecherBuffer.length,MyAddress,Integer.parseInt(txtPort.getText()));
LeecherSocket.send(dp);
System.out.println("Activation test");
//????
/*
//Receiving successful connection response
DatagramPacket DGPReceiveResponse = new DatagramPacket(LeecherBuffer,LeecherBuffer.length);
String message = "";
LeecherSocket.receive(DGPReceiveResponse);
message = new String(LeecherBuffer);
System.out.println(message);
*/
//LeecherSocket.close();
}
catch (UnknownHostException e1)
{
e1.printStackTrace();
}
catch (SocketException e1)
{
e1.printStackTrace();
}
catch (IOException e1)
{
e1.printStackTrace();
}
此外,在代码中只是为了避免任何混淆:播种机是服务器,而leecher是客户端。
有什么想法吗?谢谢。