本帖最后由 许大虾 于 2013-6-19 22:17 编辑
源码
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;
using System.Net;//包含IP,IPAdress,IPEndPoint(ip和端口)类
using System.Net.Sockets;//导入套接字
using System.Threading;
namespace MyCharRoomServer
{
public partial class FChatServer : Form
{
public FChatServer()
{
InitializeComponent();
}
Thread threadWatch = null;//负责监听客户端连接请求的线程
Socket socketWatch = null;//负责监听的套接字
private void btnBeginListem_Click(object sender, EventArgs e)
{
//创建服务端负责监听的套接字,参数(使用IP4寻址协议,使用流式连接,使用TCP协议传输数据)
Socket socketWatch = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp);
//获得文本框中的IP地址对象
IPAddress address = IPAddress.Parse(txtIP.Text.Trim());
//创建包含ip和port的网络节点对象
IPEndPoint endpoint = new IPEndPoint(address, int.Parse(txtPort.Text.Trim()));
//将负责监听的套接字 绑定到唯一的IP和端口上
socketWatch.Bind(endpoint);
//设置监听队列的长度
socketWatch.Listen(10);
//创建负责监听的线程,并传入监听方法
threadWatch = new Thread(WatchConnecting);
threadWatch.IsBackground = true;//设置为后台线程
threadWatch.Start();//开启线程
ShowMsg("服务器启动监听成功!");
//socketWatch.Bind
//IPEndPoint
}
void WatchConnecting()
{
//开始监听客户端连接请求,注意:Accept方法,会阻断当前的线程!
Socket sokConnetion = socketWatch.Accept();
ShowMsg("客户端连接成功!");
}
void ShowMsg(string msg)
{
txtMsg.AppendText(msg + "\r\n");
}
}
}
|
|