撇開Smart-ass的意見:即使你只對2行代碼感興趣,我敢打賭你的問題是在你的代碼中的其他地方。
使用發現的代碼的修改版本here,我構建了一個簡單的例子,在我的測試中起作用。
public static void Main()
{
TcpListener server = null;
try
{
// Set the TcpListener on port 13000.
Int32 port = 13000;
IPAddress localAddr = IPAddress.Parse("127.0.0.1");
// TcpListener server = new TcpListener(port);
server = new TcpListener(localAddr, port);
// Start listening for client requests.
server.Start();
// Buffer for reading data
Byte[] bytes = new Byte[256];
Console.Write("Waiting for a connection... ");
// Perform a blocking call to accept requests.
// You could also user server.AcceptSocket() here.
TcpClient client = server.AcceptTcpClient();
Console.WriteLine("Connected!");
// Get a stream object for reading and writing
NetworkStream stream = client.GetStream();
stream.Read(bytes, 0, bytes.Length);
Console.WriteLine(System.Text.Encoding.ASCII.GetString(bytes));
// Shutdown and end connection
client.Close();
}
catch (SocketException e)
{
Console.WriteLine("SocketException: {0}", e);
}
finally
{
// Stop listening for new clients.
server.Stop();
}
Console.WriteLine("\nHit enter to continue...");
Console.Read();
}
讀取調用將等待並返回時,我與另一程序1個字節的發送。我們需要看一些代碼來弄清楚爲什麼這個工作,而你的不工作。
第一:請發佈您使用的實際代碼 - 第二:嘗試關閉客戶端寫入字節後的連接,因爲我的猜測是,您正在使用*流*不是正確的方式 – Carsten 2012-04-02 04:13:48
我可以從代碼中可以看出,它很可能是由海王星發射的粒子干擾的。我強烈建議你用錫紙遮擋你的整個城市,以獲得更高質量的傳輸。 – 2012-04-02 04:18:17
第一:我已經解釋了代碼..在這個問題中,我只關注2行,我的客戶端是Network.Write,我的服務器是Network.Read。 其次,我正在創建一個連接,並從我的客戶端進行寫入操作,然後執行Read操作以獲取服務器的響應。我在那裏僵持不下。 – user1296146 2012-04-02 04:45:06