Unity套接字连接失败

时间:2016-12-18 10:34:52

标签: c# sockets unity3d

以下是我的C#服务器的代码:

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Net.Sockets;

namespace ConsoleApplication1
{
    class Program
    {
        static void Main(string[] args)
        {

            TcpListener serverSocket = new TcpListener(8888);
            TcpClient clientSocket = default(TcpClient);
            serverSocket.Start();
            Console.WriteLine(" >> Server Started");
            clientSocket = serverSocket.AcceptTcpClient();
            Console.WriteLine(" >> Accept connection from client");
//          Console.ReadLine();

            while (true) {
                String textinput;
                textinput = Console.ReadLine ();
                NetworkStream serverStream = clientSocket.GetStream ();
                byte[] outStream = System.Text.Encoding.ASCII.GetBytes (textinput + "$");
                serverStream.Write (outStream, 0, outStream.Length);
                serverStream.Flush ();
            }

            clientSocket.Close();
            serverSocket.Stop();
            Console.WriteLine(" >> exit");
            Console.ReadLine();
        }

    }
}

然后这是c#client的代码:

using System;
using System.Net.Sockets;
using System.Text; 

namespace WindowsApplication1
{
    class Form1
    {
        static void Main(string[] args)
        {
            System.Net.Sockets.TcpClient clientSocket = new System.Net.Sockets.TcpClient();
            clientSocket.Connect("10.132.198.29", 8888);
            Console.WriteLine ("Running the client");

            while ((true))
            {
                try
                {
                    NetworkStream networkStream = clientSocket.GetStream();
                    byte[] bytesFrom = new byte[10025];
                    networkStream.Read(bytesFrom, 0, (int)bytesFrom.Length);
                    string dataFromClient = System.Text.Encoding.ASCII.GetString(bytesFrom);
                    dataFromClient = dataFromClient.Substring(0, dataFromClient.IndexOf("$"));
                    Console.WriteLine(" >> Data from Server - " + dataFromClient);
                    string serverResponse = "Last Message from Server" + dataFromClient;
                    Byte[] sendBytes = Encoding.ASCII.GetBytes(serverResponse);
                    networkStream.Write(sendBytes, 0, sendBytes.Length);
                    networkStream.Flush();
                    Console.WriteLine(" >> " + serverResponse);
                }
                catch (Exception ex)
                {
                    Console.WriteLine(ex.ToString());
                }
            }
            // byte[] inStream = new byte[10025];
            // serverStream.Read(inStream, 0, (int)clientSocket.ReceiveBufferSize);

        }
    }
}

这些在终端中工作正常,但我想将客户端转换为统一项目。 所以我在Unity项目中创建了一个空对象,并将以下代码添加到脚本中(对原始c#客户端代码进行了一些更改)。

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


public class Client : MonoBehaviour {

    System.Net.Sockets.TcpClient clientSocket = new System.Net.Sockets.TcpClient();
    // Use this for initialization
    void Start () {
        System.Net.Sockets.TcpClient clientSocket = new System.Net.Sockets.TcpClient();
        clientSocket.Connect("10.132.198.29", 8888);
        Debug.Log ("Running the client");

    }

    // Update is called once per frame
    void Update () {
        try
        {
            NetworkStream networkStream = clientSocket.GetStream();
            byte[] bytesFrom = new byte[10025];
            networkStream.Read(bytesFrom, 0, (int)bytesFrom.Length);
            string dataFromClient = System.Text.Encoding.ASCII.GetString(bytesFrom);
            dataFromClient = dataFromClient.Substring(0, dataFromClient.IndexOf("$"));
            Debug.Log(" >> Data from Server - " + dataFromClient);
            string serverResponse = "Last Message from Server" + dataFromClient;
            Byte[] sendBytes = Encoding.ASCII.GetBytes(serverResponse);
            networkStream.Write(sendBytes, 0, sendBytes.Length);
            networkStream.Flush();
            Debug.Log(" >> " + serverResponse);
        }
        catch (Exception ex)
        {
            Debug.Log("Exception error:"+ex.ToString());
        }
    }
}

实际上,当我运行我的团结项目时。我可以看到服务器打印"接受来自客户端的连接"。当我更改我的IP时,统一项目将卡住..所以我认为我的团结项目已成功连接到服务器。但在统一项目中,控制台打印

Exception error:System.IO.IOException: Not connected
  at System.Net.Sockets.NetworkStream..ctor (System.Net.Sockets.Socket socket, FileAccess access, Boolean owns_socket) [0x00000] in <filename unknown>:0 
  at System.Net.Sockets.NetworkStream..ctor (System.Net.Sockets.Socket socket, Boolean owns_socket) [0x00000] in <filename unknown>:0 
  at (wrapper remoting-invoke-with-check) System.Net.Sockets.NetworkStream:.ctor (System.Net.Sockets.Socket,bool)
  at System.Net.Sockets.TcpClient.GetStream () [0x00000] in <filename unknown>:0 
  at Client.Update () [0x00000] in /Users/User/Unity3D/ClientTest/Assets/Client.cs:23 
UnityEngine.Debug:Log(Object)
Client:Update() (at Assets/Client.cs:37)

当我在服务器的终端输入内容时,它无法在统一项目控制台上打印任何内容。任何人都可以帮忙......很长一段时间都很困惑......

1 个答案:

答案 0 :(得分:0)

使用线程进行异步等待。像这样:

    System.Threading.Thread SocketThread;
volatile bool keepReading = false;

// Use this for initialization
void Start()
{
    Application.runInBackground = true;
    startServer();
}

void startServer()
{
    SocketThread = new System.Threading.Thread(networkCode);
    SocketThread.IsBackground = true;
    SocketThread.Start();
}



private string getIPAddress()
{
    IPHostEntry host;
    string localIP = "";
    host = Dns.GetHostEntry(Dns.GetHostName());
    foreach (IPAddress ip in host.AddressList)
    {
        if (ip.AddressFamily == AddressFamily.InterNetwork)
        {
            localIP = ip.ToString();
        }

    }
    return localIP;
}


Socket listener;
Socket handler;

void networkCode()
{
    string data;

    // Data buffer for incoming data.
    byte[] bytes = new Byte[1024];

    // host running the application.
    Debug.Log("Ip " + getIPAddress().ToString());
    IPAddress[] ipArray = Dns.GetHostAddresses(getIPAddress());
    IPEndPoint localEndPoint = new IPEndPoint(ipArray[0], 1755);

    // Create a TCP/IP socket.
    listener = new Socket(ipArray[0].AddressFamily,
        SocketType.Stream, ProtocolType.Tcp);

    // Bind the socket to the local endpoint and 
    // listen for incoming connections.

    try
    {
        listener.Bind(localEndPoint);
        listener.Listen(10);

        // Start listening for connections.
        while (true)
        {
            keepReading = true;

            // Program is suspended while waiting for an incoming connection.
            Debug.Log("Waiting for Connection");     //It works

            handler = listener.Accept();
            Debug.Log("Client Connected");     //It doesn't work
            data = null;

            // An incoming connection needs to be processed.
            while (keepReading)
            {
                bytes = new byte[1024];
                int bytesRec = handler.Receive(bytes);
                Debug.Log("Received from Server");

                if (bytesRec <= 0)
                {
                    keepReading = false;
                    handler.Disconnect(true);
                    break;
                }

                data += Encoding.ASCII.GetString(bytes, 0, bytesRec);
                if (data.IndexOf("<EOF>") > -1)
                {
                    break;
                }

                System.Threading.Thread.Sleep(1);
            }

            System.Threading.Thread.Sleep(1);
        }
    }
    catch (Exception e)
    {
        Debug.Log(e.ToString());
    }
}

void stopServer()
{
    keepReading = false;

    //stop thread
    if (SocketThread != null)
    {
        SocketThread.Abort();
    }

    if (handler != null && handler.Connected)
    {
        handler.Disconnect(false);
        Debug.Log("Disconnected!");
    }
}

void OnDisable()
{
    stopServer();
}

从这里得到它:Unity3d C# plugin to act as a socket server

相关问题