首页 > 解决方案 > C# - 无法连接我的套接字服务器

问题描述

下午好亲爱的社区,

我目前正在开发一个 Arduino + Unity 项目,我应该通过 Unity 构建一个 Arduino 控件。为此,我设置了我的 Arduino 并连接到 wifi。

我用 C# 构建了一个 Socket 服务器。问题是:我能够通过 Node.js Socket Client 连接到这个 Socket Server,但是为了检查我的 Arduino 设置是否损坏,我构建了一个 Node.js Socket Server 并且能够连接我的 Node.js Socket 服务器通过 Arduino 成功。(我在这里使用 Node.js 的唯一原因是因为我在那个平台上更流利,所以我能够检查出了什么问题,所以最终项目没有任何 Node.js。)所以;

Node.js 客户端 -> Unity C# 服务器(工程)

Arduino 客户端 -> Node.js 服务器(工程)(下面是 Arduino 输出)

AT+CIPSTART=3,"TCP","192.168.1.67",1234
OK
Linked

Arduino 客户端 -> Unity C# 服务器(不工作)(下面是 Arduino 输出)

AT+CIPSTART=3,"TCP","192.168.1.67",1234
ERROR
Unlink

下面是我所有的 C#、Node.js 和 Arduino 代码。我不认为这里有 Arduino 硬件问题,但不明白为什么我无法连接我的 Unity Socket 服务器。

using System;
using System.Net.Sockets;
using System.Threading;
using System.Net;
using UnityEngine;

public class SocketScript : MonoBehaviour {
    Thread tcpListenerThread;

    void Start()
    {
        tcpListenerThread = new Thread(() => ListenForMessages(1234));
        tcpListenerThread.Start();
    }

    public void ListenForMessages(int port)
    {
        TcpListener server = null;
        try
        {

            IPAddress localAddr = IPAddress.Parse("192.168.1.67");
            server = new TcpListener(localAddr, port);
            server.Start();

            Byte[] bytes = new byte[256];
            String data = null;

            while(true)
            {
                Debug.Log("Waiting for connection.");
                using (TcpClient client = server.AcceptTcpClient())
                {
                    Debug.Log("Connected!");
                    data = null;
                    NetworkStream stream = client.GetStream();
                    int i;

                    // As long as there is something in the stream:
                    while((i = stream.Read(bytes, 0, bytes.Length)) != 0)
                    {
                        // Translate data bytes to a ASCII string.
                        data = System.Text.Encoding.ASCII.GetString(bytes, 0, i);
                        Debug.Log(String.Format("Received: {0}", data));

                        byte[] msg = System.Text.Encoding.ASCII.GetBytes(data);

                        // Send back a response.
                        stream.Write(msg, 0, msg.Length);
                        Debug.Log(String.Format("Sent: {0}", data));
                    }
                }
            }

        } catch (SocketException e)
        {
            Debug.LogError(String.Format("SocketException: {0}", e));
        } finally
        {
            server.Stop();
        }
    }

}

Node.js 客户端:

var net = require('net');

var HOST = '192.168.1.67';
var PORT = 1234;

var client = new net.Socket();

client.connect(PORT, HOST, function() {
    console.log('Client connected to: ' + HOST + ':' + PORT);
    // Write a message to the socket as soon as the client is connected, the server will receive it as message from the client 
    client.write('Hello World!');

});

client.on('data', function(data) {    
    console.log('Client received: ' + data);
     if (data.toString().endsWith('exit')) {
       client.destroy();
    }
});

// Add a 'close' event handler for the client socket
client.on('close', function() {
    console.log('Client closed');
});

client.on('error', function(err) {
    console.error(err);
});

Node.js 服务器:

var net = require('net');


// Configuration parameters
var HOST = '192.168.1.67';
var PORT = 1234;

// Create Server instance 
var server = net.createServer(onClientConnected);

server.listen(PORT, HOST, function() {  
  console.log('server listening on %j', server.address());
});

function onClientConnected(sock) {  
  var remoteAddress = sock.remoteAddress + ':' + sock.remotePort;
  console.log('new client connected: %s', remoteAddress);

  sock.on('data', function(data) {
    console.log('%s Says: %s', remoteAddress, data);
    sock.write(data);
    sock.write(' exit');
  });

  sock.on('close',  function () {
    console.log('connection from %s closed', remoteAddress);
  });

  sock.on('error', function (err) {
    console.log('Connection %s error: %s', remoteAddress, err.message);
  });
};

标签: c#node.jssocketsunity3darduino

解决方案


推荐阅读