namespace TCPServer

{
public partial
class Form1 : Form

{
public Form1()

{

InitializeComponent();

}
public bool btnstatu =
true;
//开始停止服务按钮状态
public Thread myThread;
//声明一个线程实例
public Socket newsock;
//声明一个Socket实例
public Socket Client;
public IPEndPoint localEP;
public int localPort;
public bool m_Listening;
//用来设置服务端监听的端口号
public int setPort

{

get {
return localPort; }

set { localPort = value; }

}
//用来往richtextbox框中显示消息
public void showClientMsg(
string msg)

{

showClientMsg(msg+
"\r\n");

}
//监听函数
public void Listen()

{
//设置端口 
setPort=
int.Parse(serverport.Text.Trim());
//初始化SOCKET实例 
newsock =
new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp);
//初始化终结点实例 
localEP=
new IPEndPoint(IPAddress.Any,setPort);
try 
{
//绑定 
newsock.Bind(localEP);
//监听 
newsock.Listen(10);
//用于设置按钮状态 
m_Listening =
true;
//开始接受连接,异步。 
newsock.BeginAccept(
new AsyncCallback(OnConnectRequest), newsock);

}
catch (Exception ex)

{

showClientMsg(ex.Message);

}

}
//当有客户端连接时的处理
public void OnConnectRequest(IAsyncResult ar)

{
//初始化一个SOCKET,用于其它客户端的连接 
Socket server1 = (Socket)ar.AsyncState;

Client = server1.EndAccept(ar);
//将要发送给连接上来的客户端的提示字符串
string strDateLine =
"Welcome here";

Byte[] byteDateLine = System.Text.Encoding.ASCII.GetBytes(strDateLine);
//将提示信息发送给客户端 
Client.Send(byteDateLine, byteDateLine.Length, 0);
//等待新的客户端连接 
server1.BeginAccept(
new AsyncCallback(OnConnectRequest), server1);
while (
true)

{
int recv = Client.Receive(byteDateLine);
string stringdata = Encoding.ASCII.GetString(byteDateLine, 0, recv);

DateTimeOffset now = DateTimeOffset.Now;
//获取客户端的IP和端口
string ip = Client.RemoteEndPoint.ToString();
if (stringdata ==
"STOP")

{
//当客户端终止连接时 
showinfo.AppendText(ip+
"已从服务器断开");
break;

}
//显示客户端发送过来的信息 
showinfo.AppendText(ip +
" " + now.ToString(
"G") +
" " + stringdata +
"\r\n");

}

}
//开始停止服务按钮
private void startService_Click(
object sender, EventArgs e)

{
//新建一个委托线程 
ThreadStart myThreadDelegate =
new ThreadStart(Listen);
//实例化新线程 
myThread =
new Thread(myThreadDelegate);
if (btnstatu)

{

myThread.Start();

statuBar.Text =
"服务已启动,等待客户端连接";

btnstatu =
false;

startService.Text =
"停止服务";

}
else 
{
//停止服务(功能还有问题,无法停止) 
m_Listening =
false;

newsock.Close();

myThread.Abort();

showClientMsg(
"服务器停止服务");

btnstatu =
true;

startService.Text =
"开始服务";

statuBar.Text =
"服务已停止";

m_Listening =
false;

}

}
//窗口关闭时中止线程。
private void Form1_FormClosing(
object sender, FormClosingEventArgs e)

{
if (myThread !=
null)

{

myThread.Abort();

}

}

}

}
yhy785864861 2012-05-02
mikemit 2010-06-02
zhupengyue 博主 回复了 mikemit 2010-06-04
lvoqxw 2010-06-02
zhupengyue 博主 回复了 lvoqxw 2010-06-04
tr110223 2010-06-02