110,561
社区成员
发帖
与我相关
我的任务
分享
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Net.Sockets;
using System.Net;
using System.Threading;
using System.Text.RegularExpressions;
namespace SocketServer
{
class Program
{
static byte[] buffer = new byte[1024];
static IDictionary<Socket, byte[]> socketClientSesson = new Dictionary<Socket, byte[]>();
static void Main(string[] args)
{
var socket = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp);
socket.Bind(new IPEndPoint(IPAddress.Parse("192.168.0.103"), 4001));
socket.Listen(500);
while (true)
{
IAsyncResult result = socket.BeginAccept(new AsyncCallback(ClientAccepted), socket);
result.AsyncWaitHandle.WaitOne();
};
}
public static void ClientAccepted(IAsyncResult ar)
{
if (!ar.IsCompleted)
{
return;
}
var socket = ar.AsyncState as Socket;
var client = socket.EndAccept(ar);
socketClientSesson.Add(client, buffer);
if (client.Connected)
{
try
{
Console.WriteLine(Encoding.Unicode.GetBytes("Message from server at " + DateTime.Now.ToString()));
}
catch (SocketException ex)
{
Console.WriteLine(ex.Message);
}
client.BeginReceive(buffer, 0, buffer.Length, SocketFlags.None, new AsyncCallback(ReceiveMessage), client);
socket.BeginAccept(new AsyncCallback(ClientAccepted), socket);
}
else
{
Console.WriteLine("Client is disconnected, the timer is stop.");
}
}
public static void ReceiveMessage(IAsyncResult ar)
{
try
{
var socket = ar.AsyncState as Socket;
if (socket == null || !socketClientSesson.ContainsKey(socket))
{
return;
}
var length = socket.EndReceive(ar);
byte[] buf = socketClientSesson[socket];
Array.Copy(buffer, buf, buf.Length);
ByteQueue queue = new ByteQueue();
queue.Enqueue(buf);
while (queue.Find())
{
byte[] readBuffer = queue.Dequeue();
var message = BitConverter.ToString(readBuffer);
if (message.StartsWith("FF-FF-FF-FF-CA-CB-CC-CD") && message.EndsWith("EA-EB-EC-ED"))
{
string repStr = message.Replace("-", " ");
Regex regex = new Regex("07 81 08.{24}");
MatchCollection matches = regex.Matches(repStr, 0);
if (matches.Count > 0)
{
//显示消息
Console.WriteLine(message);
}
}
}
socket.BeginReceive(buffer, 0, buffer.Length, SocketFlags.None, new AsyncCallback(ReceiveMessage), socket);
}
catch (Exception ex)
{
Console.WriteLine(ex.Message);
}
}
}
}
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Text.RegularExpressions;
using System.Net;
using System.Net.Sockets;
using System.Threading;
namespace ConsoleApplication41
{
class Program
{
Socket serverSocket;
string tempIP = "";
List<IPAddress> ipaddrssList = new List<IPAddress>();
static void Main(string[] args)
{
new Program().ServerStar();
}
/// <summary>
/// 建立连接
/// </summary>
private void ServerStar()
{
this.SocketServer("192.168.0.103", 4001);
}
/// <summary>
/// 服务端
/// </summary>
private void SocketServer(string host, int port)
{
try
{
//服务器IP地址
IPAddress ip = IPAddress.Parse(host);
serverSocket = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp);
serverSocket.Bind(new IPEndPoint(ip, port));
serverSocket.Listen(500);
Thread myThread = new Thread(ListenClientConnect);
myThread.Start();
}
catch (ArgumentNullException ex)
{
}
catch (SocketException ex)
{
}
}
/// <summary>
/// 监听客户端连接
/// </summary>
private void ListenClientConnect()
{
try
{
while (true)
{
Socket clientSocket = serverSocket.Accept();
if (clientSocket.Connected == true)
{
Thread thread = new Thread(new ParameterizedThreadStart(ReceiveMessage));
thread.Start(clientSocket);
}
}
}
catch (Exception ex)
{
}
}
/// <summary>
/// 接收消息
/// </summary>
/// <param name="clientSocket"></param>
private void ReceiveMessage(object clientSocket)
{
Socket myClientSocket = (Socket)clientSocket;
IPAddress clientIP = ((IPEndPoint)myClientSocket.RemoteEndPoint).Address;
ByteQueue queue = new ByteQueue();
int temp = 0;
while (true)
{
try
{
byte[] recvBytes = new byte[1024];
int bytes = myClientSocket.Receive(recvBytes, recvBytes.Length, 0);
byte[] reallData = new byte[bytes];
Array.Copy(recvBytes, reallData, reallData.Length);
queue.Enqueue(reallData);
while (queue.Find())
{
byte[] readBuffer = queue.Dequeue();
string data = BitConverter.ToString(readBuffer);
if (data.StartsWith("FF-FF-FF-FF-CA-CB-CC-CD") && data.EndsWith("EA-EB-EC-ED"))
{
string repStr = data.Replace("-", " ");
Regex regex = new Regex("07 81 08.{24}");
MatchCollection matches = regex.Matches(repStr, 0);
if (matches.Count > 0)
{
//显示消息
Console.WriteLine(repStr);
}
}
}
}
catch (Exception ex)
{
}
}
}
}
}
static IDictionary<Socket, ClientInfo> socketClientSesson = new Dictionary<Socket, ClientInfo>();
static void Main(string[] args)
{
var socket = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp);
socket.Bind(new IPEndPoint(IPAddress.Parse("192.168.0.103"), 4001));
socket.Listen(500);
socket.BeginAccept(new AsyncCallback(ClientAccepted), socket);
}
public static void ClientAccepted(IAsyncResult ar)
{
if (!ar.IsCompleted)
{
return;
}
var socket = ar.AsyncState as Socket;
var client = socket.EndAccept(ar);
ClientInfo info = new ClientInfo();
info.Queue = new ByteQueue();
info.Buffer = new byte[1024];
info.Socket = client;
socketClientSesson.Add(client, info);
if (client.Connected)
{
try
{
Console.WriteLine(Encoding.Unicode.GetBytes("Message from server at " + DateTime.Now.ToString()));
}
catch (SocketException ex)
{
Console.WriteLine(ex.Message);
}
client.BeginReceive(info.Buffer, 0, info.Buffer.Length, SocketFlags.None, new AsyncCallback(ReceiveMessage), client);
socket.BeginAccept(new AsyncCallback(ClientAccepted), socket);
}
else
{
Console.WriteLine("Client is disconnected, the timer is stop.");
}
}
public class ClientInfo
{
public byte[] Buffer { get; set; }
public ByteQueue Queue { get; set; }
public Socket Socket { get; set; }
}
public static void ReceiveMessage(IAsyncResult ar)
{
try
{
var socket = ar.AsyncState as Socket;
if (socket == null || !socketClientSesson.ContainsKey(socket))
{
return;
}
var length = socket.EndReceive(ar);
ClientInfo info = socketClientSesson[socket];
byte[] readBuff = new byte[length];
System.Buffer.BlockCopy(info.Buffer, 0, readBuff, 0, length);
info.Queue.Enqueue(readBuff);
while (info.Queue.Find())
{
byte[] readBuffer = info.Queue.Dequeue();
var message = BitConverter.ToString(readBuffer);
if (message.StartsWith("FF-FF-FF-FF-CA-CB-CC-CD") && message.EndsWith("EA-EB-EC-ED"))
{
string repStr = message.Replace("-", " ");
Regex regex = new Regex("07 81 08.{24}");
MatchCollection matches = regex.Matches(repStr, 0);
if (matches.Count > 0)
{
//显示消息
Console.WriteLine(message);
}
}
}
socket.BeginReceive(info.Buffer, 0, info.Buffer.Length, SocketFlags.None, new AsyncCallback(ReceiveMessage), socket);
}
catch (Exception ex)
{
Console.WriteLine(ex.Message);
}
}
}