1、服务器端画面
2.客户端软件
?
?3.所需要的using?
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;
using System.IO;
using System.Net;
using System.Net.Sockets;
using System.Threading;
4.端口监听(用try?防止抛异常)
try
{
Socket socketWatch = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp);
IPAddress ip = IPAddress.Any;
IPEndPoint point = new IPEndPoint(ip, Convert.ToInt32(txtPort.Text));
//监听
socketWatch.Bind(point);
// ShowMsg("监听成功");
socketWatch.Listen(10);
Thread th = new Thread(Listen);
th.IsBackground = true;
th.Start(socketWatch);
}
catch { }
5、调用新线程持续监听
Socket socketSend;
void Listen(object o)
{
Socket socketWatch = o as Socket;
while (true)
{
try
{
socketSend = socketWatch.Accept();
dicsocket.Add(socketSend.RemoteEndPoint.ToString(), socketSend);
cboUser.Items.Add(socketSend.RemoteEndPoint.ToString());
cboUser.SelectedIndex = 0;
ShowMsg(socketSend.RemoteEndPoint.ToString() + ":" + "连接成功");
labifon.Text = "连接成功";
myline(labifon.Text);
labifon.ForeColor = Color.Blue;
Thread th = new Thread(Recive);
th.IsBackground = true;
th.Start(socketSend);
// IPEndPoint clienip = (IPEndPoint)socketSend.RemoteEndPoint;
// txtIP.Text = clienip.Address.ToString();
}
catch { }
}
}
6.接收监听到数据
Dictionary<string, Socket> dicsocket = new Dictionary<string, Socket>();
void Recive(object o)
{
Socket socketSend = o as Socket;
byte[] buffer = new byte[1024 * 1024 * 2];
while (true)
{
// r 实际接收到的字节数
int r = socketSend.Receive(buffer);
if (r == 0)
{
labifon.Text = "连接断开";
myline(labifon.Text);
labifon.ForeColor = Color.Red;
txtLog.Text = null;
break;
}
else
{
}
string str = Encoding.UTF8.GetString(buffer, 0, r);//接收到的字节 按指定编码转换成字符串
// txtRev.Text = (socketSend.RemoteEndPoint + ":" + str);//把接收到字符显示到 文本框中
torev(str);
a = a + r;
labRev.Text =a.ToString();
txtRev.AppendText(socketSend.RemoteEndPoint + ""+ System.DateTime.Now.ToString("T") + "--->" + str + "\r\n");//转换后的字符串显示到文本框中
}
}
7、给客户端发送数据?
private void Sendmsg()
{
Form1.Sendbtn = "0";
tosend(txtMsg.Text);
try
{
string str = txtMsg.Text.Trim();
byte[] buffer = System.Text.Encoding.UTF8.GetBytes(str);
txtRev.AppendText(socketSend.RemoteEndPoint + "" + System.DateTime.Now.ToString("T") + "<---" + str + "\r\n");
socketSend.Send(buffer);
}
catch { }
}
真实项目,代码可用。转载留源。
|