Unity套接字连接失败 [英] Unity socket connection failed

查看:156
本文介绍了Unity套接字连接失败的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

这是我的C#服务器的代码:

Here is the code for my C# server:

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#客户端的代码:

Then here is the code for 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项目. 因此,我在Unity项目中创建了一个空对象,然后将以下代码添加到脚本中(对原始c#客户端代码进行了一些更改).

These all works fine in the terminal, but I want to convert the client into the unity project. So I create an empty object in my Unity project, and add the following code to the script, (made the few changes for the original c# client code).

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时,统一项目将卡住.因此,我认为我的统一项目已成功连接到服务器.但是在统一项目中,控制台会打印

Actually, when I run my unity project. I can see the server print "Accept connection from client". When I change my ip, the unity project will stuck..So I think my unity project have successfully connected to the server. But in the unity project, the console print

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)

当我在服务器终端中键入内容时,它无法在unity项目控制台上打印任何内容.任何人都可以帮忙...很长时间了...

When I type something in the server's terminal, it cannot print anything on the unity project console.. Can anyone help... Quite confused for a long time...

推荐答案

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

Use threads for async waits. Like this:

    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#插件充当套接字服务器

这篇关于Unity套接字连接失败的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆