Issues with Unity and .NET Sockets

Hi,

I’m having issues with getting Unity to connect to a server via sockets. Right now I’m just using basic tutorials to try and work out how to achieve this. Right now I have a really simple server which I’ve written using C# with a WinForms front end and another simple client to test the server.

Server Class (which runs on a thread created in the main form):


class ServerLogic
    {
        bool m_running;
        const int PORT_NUM = 10000;
        private TcpListener listener;

            private SimpleSimulation currentSim;
    
            private string m_log;
            
            public ServerLogic(SimpleSimulation sim)
            {
                m_log = "";
                m_running = true;
                currentSim = sim;
            }
    
            public void DoListen()
            {
                try
                {
                    // Listen for new connections.
                    Byte[] bytes = new Byte[256];
                    String data = null;
                    
                    listener = new TcpListener(System.Net.IPAddress.Any, PORT_NUM);
                    listener.Start();
                    m_log += "Listening!

";

                    while(m_running)
                    {
                        if (listener.Pending())
                        {
                            Socket soc = listener.AcceptSocket();
                            m_log += "Connected!

";
data = null;

                            // Get a stream object for reading and writing
                            NetworkStream stream = new NetworkStream(soc);
    
                            int i;
    
                            // Loop to receive all the data sent by the client.
                            while ((i = stream.Read(bytes, 0, bytes.Length)) != 0)
                            {
                                // Translate data bytes to a ASCII string.
                                data = System.Text.Encoding.ASCII.GetString(bytes, 0, i);
                                m_log += String.Format("Received: {0}

", data);

                                // Process the data sent by the client.
                                string response = processData(data); //Works out a response string based on the request from the client
    
                                byte[] msg = System.Text.Encoding.ASCII.GetBytes(response);
    
                                // Send back a response.
                                stream.Write(msg, 0, msg.Length);
                                m_log += String.Format("Sent: {0}

", data);
}

                            soc.Close();
                        }
                     }
                }
                catch (Exception ex)
                {
                    MessageBox.Show(ex.ToString());
                }
            }
        }

And the client code:


private void Connect(String server, String message)
        {
            try
            {
                Int32 port = 10000;
                TcpClient client = new TcpClient(server, port);

                Byte[] data = System.Text.Encoding.ASCII.GetBytes(message);

                // Get a client stream for reading and writing.

                NetworkStream stream = client.GetStream();

                // Send the message to the connected TcpServer. 
                stream.Write(data, 0, data.Length);
                
                // Receive the TcpServer.response.

                // Buffer to store the response bytes.
                data = new Byte[256];

                // String to store the response ASCII representation.
                String responseData = String.Empty;

                // Read the first batch of the TcpServer response bytes.
                Int32 bytes = stream.Read(data, 0, data.Length);
                responseData = System.Text.Encoding.ASCII.GetString(data, 0, bytes);
                MessageBox.Show(responseData);
                // Close everything.
                
                stream.Close();
                client.Close();
            }
            catch (ArgumentNullException e)
            {
                Console.WriteLine("ArgumentNullException: {0}", e);
            }
            catch (SocketException e)
            {
                Console.WriteLine("SocketException: {0}", e);
            }
        }

        private void button1_Click(object sender, EventArgs e)
        {
            Connect("192.168.1.2", "ENTITIES");
        }

        private void button2_Click(object sender, EventArgs e)
        {
            Connect("192.168.1.2", "COUNT");
        }

This code (which is all just pure C# and .NET) is working great. The server tells me there was a connection and the client receives the data (yay!). It all falls apart when I put it in Unity however. My Unity script currently looks like this:


using UnityEngine;
using System;
using System.IO;
using System.Collections;
using System.Net.Sockets;
using System.Net;

public class Client : MonoBehaviour {

	// Use this for initialization
	public string server = "127.0.0.1";
	public int port = 10000;
	
	void Start () 
	{
        try
        {
            TcpClient client = new TcpClient(server, port);

            Debug.Log("Connected: " + client.Connected);

            byte[] messageData = System.Text.Encoding.ASCII.GetBytes("COUNT");

            NetworkStream stream = client.GetStream();
            stream.Write(messageData, 0, messageData.Length);

        //NOTE: The response portion is commented out because I need to do it
        //with an AsyncCallback

        //byte[] responseData = new byte[256];
        //Int32 bytes = stream.Read(responseData, 0, responseData.Length);
        //string response = System.Text.Encoding.ASCII.GetString(responseData, 0, bytes);
        //Debug.Log(response);
        }
        catch (Exception e)
        {
            Debug.Log(e.InnerException.Message);
        }
	}
	
	// Update is called once per frame
	void Update () 
	{
		
	}
}

This script is just attached to an empty GameObject in an empty scene and the code is almost exactly what I had in the client (which worked) however nothing is happening. The server isn’t registering a connection and I can’t work out what is different between the Client code I wrote in C#/WinForm and the code I wrote in Unity.

Any help would be greatly appreciated!

Cheers!

I think I’ve solved it. It seems to be an issue with the port number I’ve used. I changed it to something else and it’s working now.