using System;
using System.Collections.Generic;
using System.Linq;
using System.Net;
using System.Net.Sockets;
using System.Text;
using System.Threading.Tasks;
namespace EchoServer0328
{
public class ClientState
{
public Socket socket;
public byte[] readBuffer = new byte[1024];
}
internal class EchoServer
{
public const int port = 8888;
static Socket serverSocket;
static Dictionary clientDictionary = new Dictionary();
static void Main()
{
serverSocket = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp);
serverSocket.Bind(new IPEndPoint(IPAddress.Any, port));
serverSocket.Listen(10);
Console.WriteLine("服务器启动成功");
serverSocket.BeginAccept(AcceptCallBack, serverSocket);
Console.Read();
}
private static void AcceptCallBack(IAsyncResult ar)
{
Socket listenSocket = ar.AsyncState as Socket;
Socket clientSocket = listenSocket.EndAccept(ar);
Console.WriteLine("新的客户端接入"+ clientSocket.RemoteEndPoint);
ClientState state = new ClientState();
state.socket = clientSocket;
clientDictionary.Add(clientSocket, state);
//开始接收
clientSocket.BeginReceive(state.readBuffer, 0, state.readBuffer.Length, 0, ReceiveCallBack, state);
//再次开始接受连接,循环接受
serverSocket.BeginAccept(AcceptCallBack, serverSocket);
}
///
/// 接收回调
///
///
private static void ReceiveCallBack(IAsyncResult ar)
{
try
{
ClientState state = ar.AsyncState as ClientState;
Socket clientSocket = state.socket;
int length = clientSocket.EndReceive(ar);
if (length == 0)
{
clientSocket.Close();
clientDictionary.Remove(clientSocket);
Console.WriteLine("客户端关闭连接"+ clientSocket.RemoteEndPoint);
return;
}
string receiveString = Encoding.Default.GetString(state.readBuffer, 0, length);
receiveString = clientSocket.RemoteEndPoint +":"+ receiveString;
receiveString.Trim();
byte[] sendBuffer = Encoding.Default.GetBytes(receiveString);
//单发
//clientSocket.Send(sendBuffer);
//群发
foreach (var item in clientDictionary.Values)
{
item.socket.Send(sendBuffer);
}
//再次开始接收数据,循环接收
clientSocket.BeginReceive(state.readBuffer, 0, state.readBuffer.Length, 0, ReceiveCallBack, state);
}
catch (Exception ex)
{
Console.WriteLine("接收失败+" + ex.Message);
}
}
#region 同步服务器
//static void Main(string[] args)
//{
// Socket socketListen = new Socket(AddressFamily.InterNetwork,SocketType.Stream,ProtocolType.Tcp);
// socketListen.Bind(new IPEndPoint(IPAddress.Any,8888));
// socketListen.Listen(0);
// Console.WriteLine("服务器启动成功");
// while (true)
// {
// Socket socketConnect = socketListen.Accept();
// Console.WriteLine("新客户端连接" );
// byte[] receiveBuffer = new byte[1024];
// int length = socketConnect.Receive(receiveBuffer);
// string receiveString = Encoding.Default.GetString(receiveBuffer,0,length);
// Console.WriteLine("收到数据:"+ receiveString);
// byte[] sendBuffer = Encoding.Default.GetBytes(receiveString);
// socketConnect.Send(sendBuffer);
// }
//}
#endregion
}
}