本项目为一个使用C#语言开发的Socket技术实现的在线聊天室示例程序,展示如何创建服务器与客户端进行实时通信。适合学习网络编程的基础应用。
namespace ChatNDraw
{
public partial class ChatNDrawForm : Form
{
LoginForm _frmLogin = new LoginForm();
SelectRoomForm _frmSelectRoom = new SelectRoomForm();
private List _strokeList = new List();
private List _endgoing = new List();
private bool _drawing = false;
private Point _startDraw = new Point();
private Bitmap _buffer = new Bitmap(333, 131);
public DateTime _started;
public ChatNDrawForm()
{
InitializeComponent();
Control.CheckForIllegalCrossThreadCalls = false;
}
private void btnConnect_Click(object sender, EventArgs e)
{
switch (_frmLogin.ShowDialog())
{
case DialogResult.OK: // 使用的是一个已经存在的账号登录
connection.Host = _frmLogin.txtHost.Text;
connection.Port = (int)_frmLogin.numPort.Value;
try
{
connection.Active = true;// 连接到服务器端
connection.Login(_frmLogin.txtUserName.Text, _frmLogin.txtPassword.Text);
EnableLoginControls(false);
}
catch(Exception error)
{
MessageBox.Show(error.Message, 聊天是服务器连接错误!);
}
break;
case DialogResult.Yes: // 创建一个新的用户连接
connection.Host = _frmLogin.txtHost.Text;
connection.Port = (int)_frmLogin.numPort.Value;
try
{
connection.Active = true;// 连接到服务器端
connection.LoginNew(_frmLogin.User);
EnableLoginControls(false);
}
catch(Exception error)
{
MessageBox.Show(error.Message, 聊天是服务器连接错误!);
}
break;
}
}
}
}