C# 从 TcpClient 读取流 [英] C# Reading stream from TcpClient
本文介绍了C# 从 TcpClient 读取流的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我正在使用 TcpClient
和服务器制作服务器 - 客户端程序.
I'm making a server - client program using TcpClient
and server.
从我使用的服务器发送:
To send from the server I use:
static void send(string data)
{
sw.WriteLine(data + Environment.NewLine);
}
当客户端连接时,我会发送一些文本:
And when the client connects I'm sending some text:
client = listener.AcceptTcpClient();
sr = new StreamReader(client.GetStream());
sw = new StreamWriter(client.GetStream());
string line;
try
{
send("Hello world");
} //More code
并从客户端读取:
string data;
data = sr.ReadLine();
if(data != string.Empty || data != null)
{
MessageBox.Show(data);
}
我尝试放入 while(true) 后它冻结了,我尝试放入一个计时器滴答循环后它冻结了...
I tried putting inside while(true) and it froze, I tried putting inside a timer tick loop and it froze...
我该如何解决这个问题?
How do I fix this?
P.S:客户端和服务器是两个不同的项目.
P.S: The client and the server are 2 different projects.
推荐答案
我相信你需要这样的东西:
I believe you need something like this:
try
{
listen = new TcpListener(myAddress, port);
listen.Start();
Byte[] bytes;
while (true)
{
TcpClient client = listen.AcceptTcpClient();
NetworkStream ns = client.GetStream();
if(client.ReceiveBufferSize > 0){
bytes = new byte[client.ReceiveBufferSize];
ns.Read(bytes, 0, client.ReceiveBufferSize);
string msg = Encoding.ASCII.GetString(bytes); //the message incoming
MessageBox.Show(msg);
}
}
}
catch(Exception e)
{
//e
}
然后将此代码作为后台线程:
Then have this code as a background thread:
Thread thread = new Thread(the functions name);
thread.IsBackground = true;
thread.Start();
我希望我了解您的需求.
I hope I understand what you need.
这篇关于C# 从 TcpClient 读取流的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文