聊天室代码问题
我做了个聊天室,但是连接的时候可以完成操作,但是当客户端发送信息给服务端的时候,服务器却接受不到信息,下面是代码:客户端:
//用于创建连接的
private void button1_Click(object sender, EventArgs e)
{
so = new Socket(AddressFamily.InterNetwork,SocketType.Stream,ProtocolType.Tcp);
so.Connect(IPAddress.Parse(textBox1.Text),34567);
if (so.Connected)
{
MessageBox.Show("已经连接了");
netw = new NetworkStream(so);
str = new StreamReader(netw);
stw = new StreamWriter(netw);
th = new Thread(new ThreadStart(this.stree));
th.Start();
}
else
{
MessageBox.Show("服务器没有开启");
}
}
//上面多线程调用的函数,用来接受对方的信息
public void stree()
{
while (so.Connected)
{
try
{
string tem = str.ReadLine();
if (tem.Length != 0)
{
lock(this){
listBox1.Items.Add("他说:" + tem);
}
}
}
catch
{
MessageBox.Show("连接断开");
}
}
so.Close();
}
//用于断开服务器
private void button2_Click(object sender, EventArgs e)
{
so.Close();
}
//用于发送信息给服务端
private void textBox2_KeyPress(object sender, KeyPressEventArgs e)
{
if(e.KeyChar == (char)13)
{
if (so.Connected)
{
try
{
lock (this)
{
listBox1.Items.Add("我说:" + textBox2.Text);
stw.WriteLine(textBox2.Text);
stw.Flush();
textBox2.Text = "";
}
}
catch
{
MessageBox.Show("自己连接断开");
}
}
else
{
MessageBox.Show("没有连接");
}
}
}
服务端代码:
//用来监听
private void button1_Click(object sender, EventArgs e)
{
ipp = new IPEndPoint(IPAddress.Any,34567);
so = new Socket(AddressFamily.InterNetwork,SocketType.Stream,ProtocolType.Tcp);
so.Blocking = true;
so.Bind(ipp);
so.Listen(0);
th = new Thread(new ThreadStart(this.stree));
th.Start();
}
//上面调用的多线程的程序,用来接受信息的
public void stree()
{
ru = so.Accept();
netw = new NetworkStream(ru);
str = new StreamReader(netw);
stw = new StreamWriter(netw);
while(ru.Connected)
{
try
{
string tem = str.ReadLine();
if (tem.Length != 0)
{
MessageBox.Show("程序接到信息");
lock (this)
{
listBox1.Items.Add("他说:" + tem);
}
}
}
catch
{
MessageBox.Show("服务器连接断开");
}
}
ru.Close();
so.Close();
}
//用来发送信息的
private void textBox1_KeyPress(object sender, KeyPressEventArgs e)
{
if(e.KeyChar == (char)13)
{
if (ru.Connected)
{
try
{
lock(this)
{
listBox1.Items.Add("我说:" + textBox1.Text);
textBox1.Text = "";
stw.WriteLine(textBox1.Text);
stw.Flush();
}
}
catch
{
MessageBox.Show("自身断开");
}
}
else
{
MessageBox.Show("没有建立连接");
}
}
}
//用于断开连接
private void button2_Click(object sender, EventArgs e)
{
so.Close();
}