using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading;
using System.Threading.Tasks;
using System.Net;
using System.Net.Sockets;
namespace seekyong
{
class tcpServer
{
private Socket ServerSocket = null;
private IPEndPoint endpoint = null;
private TaskFactory taskFactory;
private Queue<Action> TaskQueue;
public tcpServer(string IP, int Port)
{
TaskQueue = new Queue<Action>();
taskFactory = new TaskFactory();
endpoint = new IPEndPoint(IPAddress.Parse(IP), Port);
ServerSocket = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp);
ServerSocket.Bind(endpoint);
ServerSocket.Listen(0);
}
public void StartAccept()
{
ServerSocket.BeginAccept(AcceptCallBack, null);
}
private void AcceptCallBack(IAsyncResult ar)
{
Socket client = ServerSocket.EndAccept(ar);
Console.WriteLine("有一个客户端连接进来");
tcpClient clientSocket = new tcpClient(client, this);
clientSocket.BeginReceive();
AddTask(StartAccept);
}
public void AssignedTasks()
{
while (true)
{
if (TaskQueue.Count == 0) continue;
while (TaskQueue.Count > 0)
taskFactory.StartNew(TaskQueue.Dequeue());
}
}
public void AddTask(Action action)
{
TaskQueue.Enqueue(action);
}
}
class tcpClient
{
private Socket ClientSocket = null;
private tcpServer ServerSocket = null;
private byte[] DataBuf;
public tcpClient(Socket client, tcpServer server)
{
DataBuf = new byte[256];
this.ClientSocket = client;
this.ServerSocket = server;
}
public void BeginReceive()
{
ClientSocket.BeginReceive(DataBuf, 0, 256, SocketFlags.None, ReceiveCallBack, null);
}
private void ReceiveCallBack(IAsyncResult ar)
{
int count = ClientSocket.EndReceive(ar);
string msg = Encoding.UTF8.GetString(DataBuf, 0, count);
Console.WriteLine("接收到消息 = " + msg);
ClientSocket.BeginSend(DataBuf, 0, count, SocketFlags.None, null, null);
ServerSocket.AddTask(BeginReceive);
}
}
class Program
{
static void Main(string[] args)
{
tcpServer server = new tcpServer("192.168.179.1", 7788);
server.StartAccept();
server.AssignedTasks();
Console.ReadKey();
}
}
}