using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Net;
using System.Net.Sockets;
using System.Text;
using System.Threading;
using System.Threading.Tasks;
using System.Windows.Forms;
namespace _06服务器监听
{
public partial class Form1 : Form
{
public Form1()
{
InitializeComponent();
}
private void Form1_Load(object sender, EventArgs e)
{
//程序加载的时侯取消跨线程检查
Control.CheckForIllegalCrossThreadCalls = false;
}
private void btnStart_Click(object sender, EventArgs e)
{
//创建一个负责监听的Socket
Socket socketWatch = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp);//用的是IPV4的TCP/IP协议
//创建IP地址和端口号
IPAddress ip = IPAddress.Any;
//创建端口号
IPEndPoint point = new IPEndPoint(ip, Convert.ToInt32(txtPort.Text));
//让负责监听的socket绑定这个IP和端口号
socketWatch.Bind(point);
//监听成功信息输出
showMsg("111");
//设置监听队列;
socketWatch.Listen(10);//在某一时间段同时连接的数量。
//创建多线程
Thread th = new Thread(Listen);
th.IsBackground = true;
th.Start(socketWatch);
}
//监听信息输出
void showMsg(string str)
{
txtLog.AppendText(str + "\r\n");
}
//创建多线程
void Listen(object s)
{
//将传来的参数强转成Socket类型
Socket socketWatch = s as Socket;
//负责监听socket来接受客户端的连接,创建跟客户端通信的socket
while (true)
{
Socket socketSend = socketWatch.Accept();
showMsg(socketSend.RemoteEndPoint.ToString() + "连接成功!");
}
}
}
}