Socket的实际应用
SocketServer:
private void btnStartListen_Click(object sender, EventArgs e)
{
Socket socketWatch = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp);
IPAddress ip = IPAddress.Parse(this.txtIP.Text);//IPAddress.Any;//new IPAddress(Encoding.Default.GetBytes(this.txtIP.Text));
IPEndPoint point = new IPEndPoint(ip, Convert.ToInt32(this.txtPort.Text));
socketWatch.Bind(point);
txtLog.AppendText("监听成功!\r\n");
socketWatch.Listen(10);
Thread th = new Thread(Listens);
th.IsBackground = true;
th.Start(socketWatch);
}
void Listens(object o)
{
Socket socketWatch = o as Socket;
//循环等待客户端链接,并新创建一个发送Socket
while (true)
{
Socket socketSend = socketWatch.Accept();
txtLog.AppendText(socketSend.RemoteEndPoint.ToString() + ":" + "链接成功!\r\n");
Thread th = new Thread(Recive);
th.IsBackground = true;
th.Start(socketSend);
}
}
Socket socketSend;
void Recive(object o)
{
socketSend = o as Socket;
while (true)
{
byte[] buffer = new byte[1024 * 1024 * 5];
int r = socketSend.Receive(buffer);
if (r == 0)
{
break;
}
string str = Encoding.Default.GetString(buffer, 0, r);
txtLog.AppendText(socketSend.RemoteEndPoint.ToString() + ":" + str);
}
}
private void Form1_Load(object sender, EventArgs e)
{
Control.CheckForIllegalCrossThreadCalls = false;
}
private void btnSendMsg_Click(object sender, EventArgs e)
{
byte[] buffer = Encoding.Default.GetBytes(this.txtWriteMsg.Text.Trim());
int r = socketSend.Send(buffer);
}
SocketClient:
Socket socketSend;
private void Form1_Load(object sender, EventArgs e)
{
Control.CheckForIllegalCrossThreadCalls = false;
}
private void btnConnet_Click(object sender, EventArgs e)
{
socketSend = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp);
IPAddress ip = IPAddress.Parse(this.txtIP.Text); //IPAddress.Any;//new IPAddress(Encoding.Default.GetBytes(this.txtIP.Text));
IPEndPoint point = new IPEndPoint(ip, Convert.ToInt32(this.txtPort.Text));
socketSend.Connect(point);
txtLog.AppendText("链接成功!\r\n");
Thread th = new Thread(Recive);
th.IsBackground = true;
th.Start();
}
void Recive()
{
while (true)
{
byte[] buffer = new byte[1024 * 1024 * 5];
int r = socketSend.Receive(buffer);
string str = Encoding.Default.GetString(buffer, 0, r);
this.txtLog.AppendText(socketSend.RemoteEndPoint.ToString() + ":" + str + "\r\n");
}
}
private void btnSendMsg_Click(object sender, EventArgs e)
{
byte[] buffer = Encoding.Default.GetBytes(this.txtWriteMsg.Text.Trim());
socketSend.Send(buffer);
}