C#tcplistener错误 [英] C# tcplistener error
本文介绍了C#tcplistener错误的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
public void timer1_Tick(object sender, EventArgs e)
{
try
{
if (listener.Pending() == true)
{
message = "";
client = listener.AcceptTcpClient();
StreamReader reader = new StreamReader(client.GetStream());
while (reader.Peek() > -1)
{
// I got an error in this code ->>//
message = (message + Convert.ToChar(reader.Read()).ToString);
}
this.Focus();
rtbConversation.Text = (rtbConversation.Text
+ (message + "\r\n"));
//p_objSynth.SelectVoice(cmbInstalled.Text)
//p_objSynth.SpeakAsync(TextBox3.Text)
}
}
catch (Exception ex)
{
MessageBox.Show(ex.Message);
}
}
推荐答案
首先,为什么在Timer Tick事件中使用此代码?这是一种糟糕的方式来监听连接,因为您只能以计时器的滴答速度接受连接.
其次,您对message
的使用非常混乱.由于无法修改字符串,因此在每次读取字符时,都需要分配一个新的字符串对象,将数据从旧字符串复制到新实例,然后删除旧字符串.请改用StringBuilder.
最后,StreamReader.Read(无论如何,您正在使用的重载)返回一个int
,因此您只需执行以下操作即可获得一个char
:
First, why is this code in a Timer Tick event?? That''s a lousy way to listen for connections as you can only accept connections at the rate of the timer tick.
Second, your use ofmessage
is very messy. Since you cannot modify a string, your allocating a new string object, copying the data from the old string to the new instance, then deleting the old string, ON EVERY READ OF A CHARACTER. Use a StringBuilder instead.
Lastly, StreamReader.Read (the overload that you''re using anyway) returns anint
, so you just do this to get achar
out of it:
// message should be declared as a StringBuilder.
message.Append((char)reader.Read());
这篇关于C#tcplistener错误的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文