我想建立一個聊天,基本上我使用了調用函數是什麼線程。
我能夠讀取服務器發送的內容,但我只能寫入一次。我試圖完成這一點,但不知道如何寫服務器每次服務器:
(考慮到我以前寫在控制檯應用程序的形式和服務器工作正常...即問題不是與服務器) 。Winforms,調用和有問題的按鈕
public partial class Form1 : Form
{
public Form1()
{
InitializeComponent();
Button btn1 = new Button();
btn1.Click += button1_Click;
}
StreamReader sr;
StreamWriter sw;
TcpClient connection;
private void Form1_Load(object sender, EventArgs e)
{
connection = new TcpClient("127.0.0.1", 5000);
sr = new StreamReader(connection.GetStream());
sw = new StreamWriter(connection.GetStream());
}
private void button2_Click(object sender, EventArgs e)
{
Thread t2 = new Thread(Reader);
t2.Start(connection);
}
string msg;
public void Reader(object o)
{
TcpClient con = o as TcpClient;
if (con == null)
return;
while (true)
{
msg = sr.ReadLine();
Invoke(new Action(Output));
}
}
public void Output()
{
ChatScreen.Text = msg;//set the message on the screen
}
string textinput;
private void button1_Click(object sender, EventArgs e)
{
textinput = InputLine.Text;
sw.WriteLine(textinput);// this thing, writes once, multiple clicks wont send a new line to the server :(..the problem is in this button
sw.Flush();
}
}
我以爲做的是連接按鈕,這樣就可以做多次點擊..eg btn.Click()..或在運行的WriteLine與調用線程(但我的直覺說使按鈕單擊幾次將使程序工作
以及有關這一主題,是否有任何異常情況發生(並打印到調試輸出窗口)? – Timbo 2011-02-07 10:51:09
我將我的代碼重新設置爲一個月前的版本,現在它可以工作。當我關閉應用程序時,我在invoke方法中遇到異常。這是正常的嗎? – 2011-02-07 11:04:19
我的另一個問題是我如何在winforms中創建私人消息。我想創建一些標籤/按鈕,它們會出現在側邊欄上,點擊它們,打開一個窗口,你只能與該會員聊天! – 2011-02-07 11:05:15