簡體   English   中英

使用socket讀寫

[英]Writing and reading using socket

這是我的代碼

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;
}

}

連接已創建。 但是消息沒有寫入服務器並讀取

我該怎么做

我認為您已從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不檢查是否有要上的StreamReader讀取數據的可靠方法。 所以你不想檢查 DataAvailable。 但是,如果您只是刪除它,那么當沒有更多要讀取時,代碼將在 ReadLine 上阻塞。 因此,您需要設置從流中讀取的超時時間,以便您等待的時間不會超過(例如)一毫秒:

theStream.ReadTimeout = 1;

然后,您可以使用以下內容:

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

這段代碼並不完美,我還需要改進它(例如,檢查引發了什么樣的異常,並進行適當的處​​理)。 也許總體上有更好的方法來做到這一點(我嘗試使用 Peek(),但我懷疑它返回的 -1 是在套接字關閉時,而不僅僅是在沒有更多數據可供讀取時)。 但是,這應該可以解決已發布代碼的問題,就像我遇到的那樣。 如果您發現服務器缺少數據,那么它可能位於您的讀取器流中,並且在從服務器發送新數據並存儲在流中以便 theStream.DataAvailable 返回 true 之前不會被讀取。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM