我在一本教材上找的一段聊天程序源码,调试时出现问题
关键源码如下
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Text;
using System.Windows.Forms;
using System.Net;
using System.Net.Sockets;
using System.Threading;
using System.Text;
namespace WindowsApplication1
{
public partial class Form1 : Form
{
public Form1()
{
InitializeComponent();
}
public IPAddress MyHostIP;
public IPEndPoint MyServer;
public Socket MySocket;
public bool MyChattingState;
public Socket MyAcceptSocket;
public void MyChatProcess()
{//创建聊天线程
byte[] MyReceivedByte=new byte[65];
string MyReceivedString;
if(MyAcceptSocket.Connected)
{
//this.label5.Text = "准备聊天!";
while (MyChattingState)
{
MyAcceptSocket.Receive(MyReceivedByte, MyReceivedByte.Length, SocketFlags.None);
MyReceivedString = Encoding.BigEndianUnicode.GetString(MyReceivedByte);
this.listBox1.Items.Add(MyReceivedString);
}
}
}
private void button1_Click(object sender, EventArgs e)
{//创建聊天室
Thread MyThread;
try
{
MyHostIP = IPAddress.Parse(this.textBox1.Text);
MyServer = new IPEndPoint(MyHostIP, Int32.Parse("8888"));
try
{
MySocket = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp);
MySocket.Bind(MyServer);
MySocket.Listen(50);
this.label5.Text = "服务器已经处于监听状态";
MyAcceptSocket = MySocket.Accept();
ThreadStart MyDelegate = new ThreadStart(MyChatProcess);
MyThread = new Thread(MyDelegate);
MyThread.Start();
}
catch { MessageBox.Show("sdcdsv"); }
}
catch(Exception ex)
{
this.label5.Text = ex.Message;
}
}
private void button3_Click(object sender, EventArgs e)
{//发送信息
byte[] MySentByte = new byte[65];
string MySendString;
try
{
MySendString = this.textBox2.Text + "." + this.richTextBox1.Text;
MySentByte = Encoding.BigEndianUnicode.GetBytes(MySendString.ToCharArray());
MyAcceptSocket.Send(MySentByte, MySentByte.Length, SocketFlags.None);
this.richTextBox1.Text = "";
}
catch(Exception ex)
{
this.label5.Text = ex.Message;
}
}
private void button2_Click(object sender, EventArgs e)
{//关闭聊天室
try
{
MySocket.Close();
MyAcceptSocket.Close();
this.label5.Text = "成功断开与客户端程序的连接!";
}
catch(Exception ex)
{
this.label5.Text = "客户端程序可能不存在!";
}
}
private void Form1_Load(object sender, EventArgs e)
{
MyChattingState = true;
}
}
}
当开启聊天室时,程序会死掉,初步分析,是button1_Click(object sender, EventArgs e)函数中的MyAcceptSocket = MySocket.Accept()语句导致,我是初接触网络编程,对此不懂,请问高手如何解决