更新:我修复了空指针问题,它似乎是从java程序发送的。但它似乎没有正确接收。事实上,接收线程函数只被调用一次。
我将此代码添加到C#代码中的initModel方法:
ThreadStart threadFunction = new ThreadStart(ReceiveThreadFunction);
_receiveDataThread = new Thread(threadFunction);
_receiveDataThread.Start();
我试图在java程序中点击按钮发送一个字符串。但是我收到了这个错误:
Exception in thread "AWT-EventQueue-0" java.lang.NullPointerException
at pkgfinal.Client$1.actionPerformed(Client.java:90)
此行代码发生此错误:
socket.send(sendPacket);
JAVA CODE:
public class Client extends JFrame
{
// set up GUI and DatagramSocket
public Client()
{
super( "Client" );
//enterField = new JTextField( "Type message here" );
InitGUI();
}
//GUI initializer
public void InitGUI(){
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
setSize(400,400);
//Create Panels
display = new JPanel();
//Create TextFields
enterField = new JTextField( "Type message here" );
//Create TextFields
enterField = new JTextField(12);
enterField.setFont(new Font("Tahoma", Font.PLAIN, 24));
enterField.setHorizontalAlignment(JTextField.LEFT);
messageSend = enterField.getText();
//Create button
displayButton = new JButton("Display");
displayButton.addActionListener(
new ActionListener()
{
public void actionPerformed( ActionEvent event )
{
try // create and send packet
{
//***********************************************
//Enter code to get text from the field and send as socket
//**********************************************
//String message = event.getActionCommand();
displayArea.append("\nSending packet containing: "+ messageSend+"\n");
byte[] data = messageSend.getBytes();
DatagramPacket sendPacket = new DatagramPacket(data, data.length, InetAddress.getLocalHost(), 1234);
socket.send(sendPacket);
displayArea.append( "Packet sent\n" );
displayArea.setCaretPosition( displayArea.getText().length() );
} // end try
catch ( IOException ioException )
{
displayArea.append( ioException + "\n" );
ioException.printStackTrace();
} // end catch
} // end actionPerformed
} // end inner class
); // end call to addActionListener
try // create DatagramSocket for sending and receiving packets
{
socket = new DatagramSocket();
} // end try
catch ( SocketException socketException )
{
socketException.printStackTrace();
System.exit( 1 );
} // end catch
C#服务器代码MainWindowXaml.cs:
private void WindowLoaded(object sender, RoutedEventArgs e)
{
// create an instance of our Model
model = new Model();
DataContext = model;
//this.GameGrid.DataContext = model;
SevenSegmentLED.ItemsSource = model.tileCollection;
//SET THE LOCAL PORT AND IP
model.SetLocalNetworkSettings(1234, "127.0.0.1");
}
在我的Model.cs中
//Some data that keeps track of ports and addresses
private static UInt32 _localPort;
private static String _localIPAddress;
public void SetLocalNetworkSettings(UInt32 port, String ipAddress)
{
_localPort = port;
_localIPAddress = ipAddress;
System.Diagnostics.Debug.Write("CALLED");
}
public void initModel()
{
try
{
// ***********************************************
// set up generic UDP socket and bind to local port
// ***********************************************
_dataSocket = new UdpClient((int)_localPort);
}
catch (Exception ex)
{
Debug.Write(ex.ToString());
}
ThreadStart threadFunction = new ThreadStart(ReceiveThreadFunction);
_receiveDataThread = new Thread(threadFunction);
_receiveDataThread.Start();
}
// this is the thread that waits for incoming messages
private void ReceiveThreadFunction()
{
//Setup Receive end point
IPEndPoint endPoint = new IPEndPoint(IPAddress.Any, 0);
while (true)
{
try
{
// wait for data
Byte[] receiveData = _dataSocket.Receive(ref endPoint);
// check to see if this is synchronization data
// ignore it. we should not recieve any sychronization
// data here, because synchronization data should have
// been consumed by the SynchWithOtherPlayer thread. but,
// it is possible to get 1 last synchronization byte, which we
// want to ignore
if (receiveData.Length < 2)
{
continue;
System.Diagnostics.Debug.Write("RECIEVED SOMETHING");
}
BinaryFormatter formatter = new BinaryFormatter();
String data = Encoding.ASCII.GetString(receiveData);
char[] ary = data.ToCharArray();
// update status window
//StatusTextBox = StatusTextBox + DateTime.Now + ":" + " New message received.\n";
}
catch (SocketException ex)
{
// got here because either the Receive failed, or more
// or more likely the socket was destroyed by
// exiting from the JoystickPositionWindow form
Console.WriteLine(ex.ToString());
return;
}
catch (Exception ex)
{ }
}
}
答案 0 :(得分:1)
好的,我们在此行获得了NullPointerException
:
socket.send(sendPacket);
之前我们初始化了sendPacket
这一行,所以它绝对不是那样的。那么socket
必须为空。
您从未初始化socket
!所以它为null,导致你的异常。您必须创建Socket
的实例。
该代码可能类似于:
DatagramSocket socket = new DatagramSocket();