因此,我已经使用UDP / IP协议套件创建了服务器和客户端应用程序进行通信。我可以将数据获取到服务器,但是当它到达时,我尝试将字符串解析为整数,我得到NumberFormatException,但是当我在格式之前打印字符串时,我得到的应该是“ 8”。我在下面发布了我的代码:
服务器
package udp_ip;
import java.net.DatagramPacket;
import java.net.DatagramSocket;
import java.net.InetAddress;
import java.io.*;
public class UDPServer {
static private int destport = 9999;
static private int bufsize = 1024;
private DatagramSocket serverSocket;
private InetAddress local_addr;
private UDPServer()
{
try
{
serverSocket = new DatagramSocket(destport);
}
catch(IOException ioe)
{
System.err.println("Client SOcket could not be created");
}
try
{
local_addr = InetAddress.getLocalHost();
}
catch(Exception uhe)
{
System.err.println("Uknown Host:\tLocalHost");
}
}
private InetAddress getLocalAddress()
{
return this.local_addr;
}
private DatagramSocket getSocket()
{
return serverSocket;
}
public static void main(String args[]) throws Exception
{
UDPServer server = new UDPServer();
DatagramSocket serverSocket = server.getSocket();
byte[] acceptData = new byte[bufsize];
InetAddress local_addr = server.getLocalAddress();
DatagramPacket receiveTestData = new DatagramPacket (acceptData,
acceptData.length);
serverSocket.receive(receiveTestData);
String str = new String(receiveTestData.getData());
System.out.println(str);
int num = Integer.parseInt(str);
int result = num*num;
byte[] testData = (result+"").getBytes();
DatagramPacket sendPacket = new DatagramPacket(testData,
testData.length, local_addr, receiveTestData.getPort());
serverSocket.send(sendPacket);
}
}
Client
package udp_ip;
import java.io.IOException;
import java.net.DatagramPacket;
import java.net.DatagramSocket;
import java.net.InetAddress;
public class UDPClient {
static private int destport = 9999;
static private int bufsize = 1024;
private DatagramSocket clientSocket;
private InetAddress local_addr;
private UDPClient()
{
try
{
clientSocket = new DatagramSocket();
}
catch(IOException ioe)
{
System.err.println("Client Socket could not be created");
}
try
{
local_addr = InetAddress.getLocalHost();
}
catch(Exception uhe)
{
System.err.println("Uknown Host:\tLocalHost");
}
}
private InetAddress getLocalAddress()
{
return this.local_addr;
}
private DatagramSocket getSocket()
{
return clientSocket;
}
public static void main(String args[]) throws Exception
{
UDPClient client = new UDPClient();
byte[] targetData = new byte[bufsize];
InetAddress local_addr = client.getLocalAddress();
int testSend = 8;
byte[] testTargetData = String.valueOf(testSend).getBytes();
DatagramPacket testSendPacket = new DatagramPacket(testTargetData,
testTargetData.length, local_addr, destport);
DatagramSocket clientSocket = client.getSocket();
clientSocket.send(testSendPacket);
DatagramPacket acceptTargetData = new DatagramPacket(targetData,
targetData.length);
clientSocket.receive(acceptTargetData);
String str = new String(acceptTargetData.getData());
System.out.println("Server Sent" + str);
}
}