TcpClient的问题,大家抽个空帮偶看看
TcpClient在form2里发送给服务器请求时遇到问题 有一个客户端的FORM,一个登陆按钮的click事件:
private void button4_Click(object sender, EventArgs e)
{
sendmsg = "#submit#username#" + textBox4.Text + "#password#" + textBox3.Text + "#";
_netcnn = new Thread(new ThreadStart(chkusr));
_netcnn.Start();
chkflag = 0;
while (chkflag==0)
{
continue;
}
_netcnn.Interrupt();
if (chkflag==1)
{
Form2 f2 = new Form2();
f2.f1 = this;
f2.Show();
this.Visible=false;
}
if (chkflag == 2)
{
MessageBox.Show("登陆失败,请检查用户名、密码!");
}
}
chkusr方法的代码:
private void chkusr()
{
Ccs = new Connectclass();
Boolean flag1 = Ccs.connect();
if (flag1 == false)
{
MessageBox.Show("连接服务器失败,请检查网络连接");
chkflag = 3;
return;
}
bool returnflag;
returnflag= Ccs.CheckUser(sendmsg);
if (returnflag == true)
{
chkflag = 1;
}
else
{
chkflag = 2;
}
}
这里的
Ccs.connect()方法是:
public Boolean connect()
{
try
{
myclient = new TcpClient("192.168.1.3", 1234);
myclient.ReceiveTimeout = 100;
networkStream=myclient.GetStream();
streamReader = new StreamReader(networkStream);
streamWriter = new StreamWriter(networkStream);
}
catch
{
return false;
}
return true;
}
form2的load事件
private void Form2_Load(object sender, EventArgs e)
{
string initialization = f1.Ccs.Sendcommand("#initialization#");
//string initialization = f1.turnmsg;
if (initialization == "false")
{
MessageBox.Show("Server disconnected");
}
else
{
……
}
}
这里的Sendcommand事件代码是:
public string Sendcommand(string Command)
{
try
{
string msg=Command;
streamWriter.WriteLine(msg);
streamWriter.Flush();
}
catch (Exception ee)
{
return "false";
}
string reseavemsg="";
try
{
bool flag=true;
while (flag)
{
reseavemsg = streamReader.ReadLine();
if (reseavemsg != "")
{
flag = false;
}
}
}
catch (Exception ee)
{
MessageBox.Show(ee.ToString());
return "false";
}
return reseavemsg;
}
现在的问题是,在form1里面是可以通过认证的,然后启动form2,在form2的load事件里需要一个Sendcommand事件,来请求服务端发送初始化信息,但是现在Sendcommand发送的#initialization#信息服务端根本就收不到,单步执行到streamread时,就出Exception了,不知道是不是因为在form1里面启动过连接的新线程,在线程中断以后需要重新连接,还是什么回事,大家帮帮忙啦~谢谢谢谢
后来测试发现在Sendcommand事件里面重新调用connect()方法的话是可以连接成功,这样也就是说是重新连接了,并且能收到服务端的回复,但是在服务端看是另外一个新的连接了,而不是之前在验证用户登陆时候的那个连接。