客户端 java udp 不会发送到 C# 服务器

Client java udp won't send to C# server

更新:我修复了空指针问题,它似乎是从 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.actionPerformed(Client.java:90)

此错误发生在这行代码:

          socket.send(sendPacket);

JAVA 代码:

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)
                { }

            }
        }

好的,所以我们在这一行得到一个 NullPointerException

socket.send(sendPacket);

我们之前初始化了sendPacket这一行,所以肯定不是那个。那么 socket 必须为空。

您从未初始化 socket!所以它是空的,导致你的异常。您必须创建 Socket.

的实例

该代码可能类似于:

DatagramSocket socket = new DatagramSocket();