[英]C# Reading stream from TcpClient
我正在使用TcpClient
和服务器制作服务器 - 客户端程序。
要从我使用的服务器发送:
static void send(string data)
{
sw.WriteLine(data + Environment.NewLine);
}
当客户端连接时,我正在发送一些文本:
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) 并冻结,我尝试放入计时器滴答循环并冻结...
我该如何解决?
PS:客户端和服务器是2个不同的项目。
我相信你需要这样的东西:
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
}
然后将此代码作为后台线程:
Thread thread = new Thread(the functions name);
thread.IsBackground = true;
thread.Start();
我希望我明白你需要什么。
试试这个,爷爷的方式。
int i = 0;
while (stream.DataAvailable == true)
{
bytes[i] = ((byte)stream.ReadByte());
i++;
}
data = System.Text.Encoding.ASCII.GetString(bytes, 0, i);
Console.WriteLine("Received: {0}", data);
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.