如何使用socket连续发送和接收数据?

时间:2017-11-27 07:17:29

标签: c# python sockets unity3d

我正在尝试开发Unity 3D游戏,其中Unity将不断向python客户端发送游戏数据。 python客户端将处理数据并将其发送到Unity服务器。现在我已经编写了一个只交换一条消息的c#服务器和python客户端。 c#服务器不会多次接收数据。我试图使用while循环,但它冻结Unity编辑器。我该怎么办?我是socket编程和python的新手。请帮忙。

这是我的Unity C#服务器:

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));


    }

}                                                                                        

这是我的python客户端:

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") )

0 个答案:

没有答案