接收TCP连接问题

时间:2013-09-26 18:21:58

标签: c# sockets tcp unity3d

我已设法将其设置为所以我的Unity应用程序可以接收tcp数据。但是,当我运行项目时,整个应用程序会冻结,并且在收到消息之前不会执行任何操作。然后,一旦收到消息,它就会打印出该消息,并且不允许我的客户端再次连接它。

这段代码是我的TCP阅读课程的全部内容,我在这里做的事情是否有些愚蠢?

有没有更好的方法来读取TCP数据?

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

public class TCPConnection: MonoBehaviour 
{
    public string ip_address = "";
    public int port_number = 0;

     void Start()
    {

        try
        {
            IPAddress ipAddress = IPAddress.Parse(ip_address);
            TcpListener listener = new TcpListener(ipAddress, port_number);
            listener.Start();
            print("The server is running at port " + port_number);
            print("The local end point is :" + listener.LocalEndpoint);
            print("Waiting for connection.....");

            Socket socket = listener.AcceptSocket();
            print("Connection accepted from " + socket.RemoteEndPoint);

            byte[] b = new byte[100];
            int k = socket.Receive(b);
            print("recieved...");
            for (int i = 0; i < k; i++)
                print (Convert.ToChar(b[i]));

            ASCIIEncoding ascii = new ASCIIEncoding();
            socket.Send(ascii.GetBytes("The string was recieved by the server"));
            print("\nSent ack");

        }

        catch (Exception e)
        {
            print("error...." + e.Message);
        }

    }
}

2 个答案:

答案 0 :(得分:2)

listener.AcceptSocketsocket.Receive是阻止来电。因此,您的UI冻结是正常的。在您接受第一个连接后,您再也不会再次致电listener.AcceptSocke来获取新的收藏。

使用这些方法的常用方法是使用异步调用,线程或任务。

修改

一个例子:

void Start()
{
    Task.Factory.StartNew(() =>
        {
            TcpListener listener = new TcpListener(IPAddress.Any, 12345);
            listener.Start();

            while (true)
            {
                Socket socket = listener.AcceptSocket();
                Task.Factory.StartNew(() =>
                {
                    byte[] b = new byte[100];
                    int k = socket.Receive(b);
                });
            }
        });
}

答案 1 :(得分:0)

socket.Receive(b);Accept()将阻止当前线程,直到您收到数据,您可以在此处执行以下操作:

1)创建一个接收数据的分离线程,并将其放入由主线程检查的队列中。但是,许多客户端连接都没有推荐这一点。

2)您可以使用套接字的异步方法:此处显示了一个示例:http://csharp.vanlangen.biz/network-programming/async-sockets/asyncsocketreader/ 还有一个非阻塞侦听器的示例。

异步监听器看起来像这样:

public class SocketEventArgs : EventArgs
{
    public Socket Socket { get; private set; }

    public SocketEventArgs(Socket socket)
    {
        Socket = socket;
    }
}

/// <author>Jeroen van Langen</author>
/// <source>http://http://csharp.vanlangen.biz/network-programming/async-sockets/easysocketlistener/</source>
public class EasySocketListener : IDisposable
{
    private Socket _socket;

    public void Start(int port)
    {
        _socket = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp);
        _socket.Bind(new IPEndPoint(IPAddress.Any, port));
        _socket.Listen(8);

        StartAccepting();
    }

    private void StartAccepting()
    {
        try
        {
            _socket.BeginAccept((asyncResult) =>
            {
                try
                {
                    Socket clientSocket = _socket.EndAccept(asyncResult);
                    if (OnSocketAccept != null)
                        OnSocketAccept(this, new SocketEventArgs(clientSocket));

                    StartAccepting();
                }
                catch { }
            }, null);
        }
        catch { }
    }

    public void Dispose()
    {
        if (_socket != null)
        {
            _socket.Dispose();
            _socket = null;
        }
    }

    public event EventHandler<SocketEventArgs> OnSocketAccept;
}

当连接新客户端时,将调用OnSocketAccept。