0

I am trying a develop an Unity 3D game where unity will continuously send game data to a python client. The python client will process the data and send it to Unity server. Right now I have written a c# server and python client that exchange one message only. The c# server does not receive data more than once. I have tried to use while loop, but it freezes the Unity Editor. What should I do? I am very new to socket programming and python. Please help.

This is my Unity C# server:

public class SetServer : MonoBehaviour
{

    string message = "Awake";
    public Socket socket;
    public Socket handler;
    IPAddress ip;
    public Socket clientSocket;
    const int kHostConnectionBacklog = 10;


    public void Start(){
        Application.RegisterLogCallbackThreaded (OnLog);

        Host (8765);


    }

    public void Update(){


    }

    public bool Host (int port)
    {
        Debug.Log ("Hosting on port " + port);

        socket = new Socket (AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp);

        try
        {
            socket.Bind (new IPEndPoint (IP, port));
            socket.Listen (kHostConnectionBacklog);

            socket.BeginAccept (new System.AsyncCallback (OnClientConnect), socket);


            //handler=socket.Accept();
        }
        catch (System.Exception e)
        {
            Debug.LogError ("Exception when attempting to host (" + port + "): " + e);

            socket = null;

            return false;
        }

        return true;
    }

    public IPAddress IP
    {
        get
        {
            if (ip == null)
            {
                ip=System.Net.IPAddress.Parse("107.109.211.79");
            }

            return ip;
        }
    }

    void OnLog (string message, string callStack, LogType type)
    {
        this.message = message + "\n" + this.message;
    }

    void OnClientConnect (System.IAsyncResult result)
    {
        Debug.Log ("Handling client connecting");


        try
        {

        //  socket.BeginAccept (new System.AsyncCallback (OnClientConnect), socket);
        //  Socket socket1 = (Socket)result.AsyncState;
            bool receive=false;
            Socket clientSocket = socket.EndAccept(result);

            if(clientSocket != null){
                Debug.Log("Begin Receive");
                byte[] bytes = new byte[256];
                clientSocket.Receive(bytes);
                string s = System.Text.Encoding.UTF8.GetString(bytes, 0, bytes.Length);
                Debug.Log(s);
                receive = true;
                //clientSocket.Beg

            }
            if(receive){
                String data ="Hello from Unity3D ";
                byte[] byteData = Encoding.ASCII.GetBytes(data);
                clientSocket.Send(byteData);

            }


        }
        catch (System.Exception e)
        {
            Debug.LogError ("Exception when starting new accept process: " + e);
        }
    }

    public void recv(Socket sock, byte[] buffer,int offset,int size, int timeout){
        int tickcount = Environment.TickCount;
        int received = 0;
        do{
            if(Environment.TickCount>tickcount+timeout)
                throw new Exception("Timeout");
            try{
                received += handler.Receive(buffer,offset+received,size-received,SocketFlags.None);

            }
            catch(SocketException ex){
                if(ex.SocketErrorCode==SocketError.WouldBlock || ex.SocketErrorCode==SocketError.IOPending || ex.SocketErrorCode==SocketError.NoBufferSpaceAvailable){
                    Thread.Sleep(30);
                }
                else{

                    throw ex;
                }

            }
        }
        while(received<size);


        Console.WriteLine(Encoding.UTF8.GetString(buffer));


    }

}                                                                                        

And this is my python client:

import socket   #for sockets
import sys  #for exit

try:
    s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
except socket.error:
    print ('Failed to create socket')
    sys.exit()

print ('Socket Created')

host = '107.109.211.79';
port = 8765;



s.connect((host , port))




message="Hi from Python"
data = message.encode()
try :
        #Set the whole string
        s.sendall(data)
except socket.error:
    #Send failed
    print ('Send failed')
    sys.exit()

print ('Message send successfully');
        reply = s.recv(4096)
        print(reply.decode("utf-8") )
Imran Sikder
  • 73
  • 13

0 Answers0