1

这是我的代码

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

public class s_TCP : MonoBehaviour {

internal Boolean socketReady = false;

TcpClient mySocket;
NetworkStream theStream;
StreamWriter theWriter;
StreamReader theReader;
String Host = "198.57.44.231";
Int32 Port = 1337;
string channel = "testingSona";

void Start () {   
    setupSocket();
    //string msg = "__SUBSCRIBE__"+channel+"__ENDSUBSCRIBE__";
    string msg = "Sending By Sona";
    writeSocket(msg);
    readSocket();

}
void Update () {
    //readSocket();
}

public void setupSocket() { 
    try {
        mySocket = new TcpClient(Host, Port);
        theStream = mySocket.GetStream(); 
        theWriter = new StreamWriter(theStream);
        theReader = new StreamReader(theStream);
        socketReady = true;         
    }
    catch (Exception e) {
        Debug.Log("Socket error: " + e);
    }
}
public void writeSocket(string theLine) {
    if (!socketReady)
        return;
    String foo = theLine + "\r\n";
    theWriter.Write(foo);
    theWriter.Flush();

}
public String readSocket() { 
    if (!socketReady)
        return ""; 
    if (theStream.DataAvailable){           
        string message = theReader.ReadLine();
        print(message);print(12345);
        return theReader.ReadLine();
    }
    else{print("no value");
        return "";
    }

}
public void closeSocket() {
    if (!socketReady)
        return;
    theWriter.Close();
    theReader.Close();
    mySocket.Close();
    socketReady = false;
}

}

已创建连接。但是消息没有写入服务器并读取

我该怎么做

4

1 回答 1

0

我认为您已从http://answers.unity3d.com/questions/15422/unity-project-and-3rd-party-apps.html获取此代码,但我认为此代码存在错误。我会在这里重复我在那里发布的内容。

以下代码无法正常工作:

public String readSocket() {
  if (!socketReady)
    return "";
  if (theStream.DataAvailable)
    return theReader.ReadLine();
  return "";
}

这让我头痛了好几个小时。我认为在流上检查DataAvailable并不是检查流读取器上是否有要读取的数据的可靠方法。所以你不想检查 DataAvailable。但是,如果您只是删除它,那么当没有更多要读取的内容时,代码将在 ReadLine 上阻塞。因此,您需要设置从流中读取的超时时间,这样您等待的时间不会超过(比如说)一毫秒:

theStream.ReadTimeout = 1;

然后,你可以使用类似的东西:

public String readSocket() {
    if (!socketReady)
        return "";
    try {
        return theReader.ReadLine();
    } catch (Exception e) {
        return "";
    }
}

这段代码并不完美,我还需要改进它(例如,检查引发了什么样的异常,并适当地处理它)。也许总体上有更好的方法来做到这一点(我尝试使用 Peek(),但我怀疑它返回的 -1 是在套接字关闭时,而不仅仅是在现在没有更多数据要读取的时候)。但是,这应该可以解决已发布代码的问题,就像我遇到的那样。如果您发现服务器中缺少数据,那么它可能位于您的读取器流中,并且在从服务器发送新数据并将其存储在流中以便 theStream.DataAvailable 返回 true 之前不会被读取。

于 2013-11-16T14:47:09.310 回答