嘿,亲!知识可是无价之宝呢,但咱这精心整理的资料也耗费了不少心血呀。小小地破费一下,绝对物超所值哦!如有下载和支付问题,请联系我们QQ(微信同号):78630559
本次赞助数额为: 3 元微信扫码支付:3 元
请留下您的邮箱,我们将在2小时内将文件发到您的邮箱
可以实现Client和Server互通,进行聊天类似QQ聊天~
//每一个连接的客户端必须设置一个唯一的用户名,在服务器端是把用户名和套接字保存在Dictionary<userName,ClientSocket>中
private void btnConnect_Click(object sender, EventArgs e)
{
if (String.IsNullOrWhiteSpace(txtName.Text.Trim()))
{
MessageBox.Show("请设置个用户名哦亲");
return;
}
if (txtName.Text.Length >= 17 && txtName.Text.ToString().Trim().Substring(0, 17).Equals("Server has closed"))
{
MessageBox.Show("该用户名中包含敏感词,请更换用户名后重试");
return;
}
if (clientSocket == null || !clientSocket.Connected)
{
try
{
clientSocket = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp);
if (!String.IsNullOrWhiteSpace(txtIP.Text.ToString().Trim()))
{
try
{
ipadr = IPAddress.Parse(txtIP.Text.ToString().Trim());
}
catch
{
MessageBox.Show("请输入正确的IP后重试");
return;
}
}
else
{
ipadr = IPAddress.Loopback;
}
//IPAddress ipadr = IPAddress.Parse("192.168.1.100");
clientSocket.BeginConnect(ipadr, 8080, (args) =>
{
if (args.IsCompleted) //判断该异步操作是否执行完毕
{
Byte[] bytesSend = new Byte[4096];
txtName.BeginInvoke(new Action(() =>
{
bytesSend = Encoding.UTF8.GetBytes(txtName.Text.Trim() "$"); //用户名,这里是刚刚连接上时需要传过去
if (clientSocket != null && clientSocket.Connected)
{
clientSocket.Send(bytesSend);
txtName.Enabled = false; //设置为不能再改名字了
txtSendMsg.Focus(); //将焦点放在
thDataFromServer = new Thread(DataFromServer);
thDataFromServer.IsBackground = true;
thDataFromServer.Start();
}
else
{
MessageBox.Show("服务器已关闭");
}
}));
txtIP.BeginInvoke(new Action(() =>
{
if (clientSocket != null && clientSocket.Connected)
{
txtIP.Enabled = false;
}
}));
}
}, null);
}
catch (SocketException ex)
{
MessageBox.Show(ex.ToString());
}
}
else
{
MessageBox.Show("你已经连接上服务器了");
}
}
private void btnBreak_Click(object sender, EventArgs e)
{
if (clientSocket != null && clientSocket.Connected)
{
thDataFromServer.Abort();
clientSocket.Send(Encoding.UTF8.GetBytes("$"));
clientSocket.Close();
clientSocket = null;
txtReceiveMsg.BeginInvoke(new Action(() =>
{
txtReceiveMsg.Text = Environment.NewLine "已断开与服务器的连接";
}));
txtName.BeginInvoke(new Action(() =>
{
txtName.Enabled = true;
})); //重连当然可以换用户名啦
txtIP.BeginInvoke(new Action(() =>
{
txtIP.Enabled = true;
}));
}
}