using System;
using System.Collections.Generic;
using System.Linq;
using System.Net;
using System.Net.Sockets;
using System.Text;
using System.Threading;
namespace WinRemoteDesktop
{
class TcpServer
{
//用于监听的SOCKET
Socket socketWatch;
//定义接收客户端发送消息的回调
private delegate void ReceiveMsgCallBack(string strReceive);
//声明
private ReceiveMsgCallBack receiveCallBack;
//将远程连接的客户端的IP地址和Socket存入集合中
Dictionary<string, Socket> dicSocket = new Dictionary<string, Socket>();
//用于通信的Socket
Socket socketSend;
//创建监听连接的线程
Thread AcceptSocketThread;
//接收客户端发送消息的线程
Thread threadReceive;
private SocketFlags None;
public delegate void NewMsgEventHandler(Socket s, byte[] msg);
public event NewMsgEventHandler NewMsg;
public void Start(int nport)
{
Socket tempSocket = socketWatch; //后面socketWatch.Bind(point)执行异常处理发生时,需要恢复socketWatch的值
try
{
//当点击开始监听的时候 在服务器端创建一个负责监听IP地址和端口号的Socket
socketWatch = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp);
//创建端口号
IPEndPoint point;
point = new IPEndPoint(IPAddress.Any/*IPAddress.Parse("172.23.190.10")*/, nport);
//绑定IP地址和端口号
socketWatch.Bind(point);
socketWatch.Listen(10);
//实例化回调
receiveCallBack = new ReceiveMsgCallBack(ReceiveMsg);
AcceptSocketThread = new Thread(new ParameterizedThreadStart(StartListen));
AcceptSocketThread.IsBackground = true;
AcceptSocketThread.Start(socketWatch);
}
catch (Exception ex)
{
socketWatch = tempSocket;
}
}
public void Stop()
{
if (AcceptSocketThread!=null)
{
AcceptSocketThread.Abort();
}
if (threadReceive!=null)
{
threadReceive.Abort();
}
}
/// <summary>
/// 监听线程 等待客户端的连接,并且创建与之通信用的Socket
/// </summary>
/// <param name="obj"></param>
private void StartListen(object obj)
{
Socket socketWatch = obj as Socket; //注释掉,不使用局部传递进来的SOCKET,而使用全局的socketWatch
try
{
while (true)
{
//等待客户端的连接,并且创建一个用于通信的Socket
socketSend = socketWatch.Accept(); //(阻塞式)等待连接的到来
//获取远程主机的ip地址和端口号
string strIp = socketSend.RemoteEndPoint.ToString();
dicSocket.Add(strIp, socketSend);
//定义接收客户端消息的线程
threadReceive = new Thread(new ParameterizedThreadStart(Receive));
threadReceive.IsBackground = true;
threadReceive.Start(socketSend);
}
}
catch (Exception ex)
{
//MessageBox.Show("监听线程异常:" + ex.ToString());
}
finally
{
//socketWatch.Close(); //局部定义的socket貌似不用关闭,也行
}
}
private void ReceiveMsg(string strMsg)
{
}
/// <summary>
/// 服务器端不停的接收客户端发送的消息
/// </summary>
/// <param name="obj"></param>
private void Receive(object obj)
{
Socket socketSend = obj as Socket; //总是用创建会话连接时,传递进来的socket接收数据
try
{
//客户端连接成功后,服务器接收客户端发送的消息
byte[] buffer = new byte[2048];
while (true)
{
Array.Clear(buffer, 0, buffer.Length);
//实际接收到的有效字节数
int count = socketSend.Receive(buffer);
//socketSend.Send(buffer, count, None);
if (count == 0)//count 表示客户端关闭,要退出循环
{
break;
}
else
{
NewMsg(socketSend, buffer);
//Console.WriteLine("接收的数据:"); //打印原始数据 十六进制
int tempI = 0;
foreach (var item in buffer)
{
tempI++;
Console.Write("0x" + item.ToString("X2") + " ");
if (tempI >= count)
break;
}
Console.WriteLine();
String str = Encoding.ASCII.GetString(buffer, 0, count);
//txt_Log.Invoke(receiveCallBack, string.Format("会话线程id:{2},local ip:{3} 接收远程客户端:{0}发送的消息:{1}", socketSend.RemoteEndPoint, str, Thread.CurrentThread.ManagedThreadId, socketSend.LocalEndPoint));
}
}
}
catch (Exception ex)
{
// string info = string.Format("数据接收异常1: {0}", ex.Message);
// txt_Log.Invoke(receiveCallBack, info);
// Console.WriteLine(info);
}
finally
{
//this.txt_Log.Invoke(receiveCallBack, string.Format("会话线程id:{0}退出", Thread.CurrentThread.ManagedThreadId));
}
}
public void SendBuffer(Socket socketSend, byte[] buffer)
{
if (socketSend!=null)
{
socketSend.Send(buffer, SocketFlags.None);
}
}
}
}