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.Net.Sockets;
using System.Net;
namespace Server
{
public partial class Form1 : Form
{
private List listSocket = new List();
public Form1()
{
InitializeComponent();
Control.CheckForIllegalCrossThreadCalls = false;
}
private void btnStart_Click(object sender, EventArgs e)
{
/*
* AddressFamily.InterNetwork:寻址方式
* SocketType.Stream:传输数据方式
* ProtocolType.Tcp:通信协议
*/
//1.创建一个socket对象
Socket socket = new Socket(AddressFamily.InterNetwork,SocketType.Stream,ProtocolType.Tcp);
//2.创建一个IP地址
IPAddress address =IPAddress.Parse(txtIP.Text.Trim());
//3.创建一个EndPoint
IPEndPoint ipEndPoint = new IPEndPoint(address,int.Parse(txtPort.Text));
//4.绑定一个端口:独享此端口
socket.Bind(ipEndPoint);
//5.开启监听
socket.Listen(10);
AddShow("服务器启动,开始监听。。。");
//6.开始接受客户端的连接
//此代码一执行就阻塞当前线程,等待客户端的连接
Task task = Task.Factory.StartNew(x => {
Socket serverSocket = x as Socket;
while (true)
{
//客户端一连接上之后,服务器端自动生产一个跟客户端通信的socket
Socket workSocket = serverSocket.Accept();
AddShow("有一个连接上"+workSocket.RemoteEndPoint.ToString());
workSocket.Send(Encoding.Default.GetBytes("你好"));
listSocket.Add(workSocket);
//接收消息
Task t = Task.Factory.StartNew(c => {
Socket recSocket = c as Socket;
while (true)
{
try
{
byte[] bufferData = new byte[1024 * 1024];
int length = recSocket.Receive(bufferData);
if (length <= 0)
{
AddShow(recSocket.RemoteEndPoint.ToString() + "正常退出");
listSocket.Remove(recSocket);
//客户端退出会发送一个空字节过来
recSocket.Shutdown(SocketShutdown.Both);
recSocket.Close();
return;
}
string recStr = Encoding.Default.GetString(bufferData, 0, length);
AddShow(recSocket.RemoteEndPoint.ToString());
AddShow(recStr);
}
catch (Exception ex)
{
//异常退出捕获
AddShow(recSocket.RemoteEndPoint.ToString() + "异常退出");
listSocket.Remove(recSocket);
//客户端退出会发送一个空字节过来
recSocket.Shutdown(SocketShutdown.Both);
recSocket.Close();
}
}
},workSocket);
}
},socket);
}
public void AddShow(string message)
{
//判断现在线程是否是创建txtShow的线程
if (txtShow.InvokeRequired)
{
//在拥有该线程的句柄上去执行
txtShow.Invoke(() =>
{
this.txtShow.Text += message + "\r\n";
});
}
else
{
this.txtShow.Text += message + "\r\n";
}
}
private void btnSend_Click(object sender, EventArgs e)
{
string str = txtMsg.Text.Trim();
byte[] data = Encoding.Default.GetBytes(str);
//群发消息
foreach (Socket item in listSocket)
{
item.Send(data);
}
}
}
}