81 lines
2.3 KiB
C#
81 lines
2.3 KiB
C#
using System;
|
|
using System.Collections.Generic;
|
|
using System.Linq;
|
|
using System.Net;
|
|
using System.Net.Sockets;
|
|
using System.Text;
|
|
using System.Threading;
|
|
using System.Threading.Tasks;
|
|
|
|
namespace DoAn.Core
|
|
{
|
|
public class SocketServerManager
|
|
{
|
|
private string ip;
|
|
private int port;
|
|
private Socket socketWatch = null;
|
|
private Socket acceptSocket = null;
|
|
private Thread threadWatch = null;
|
|
|
|
public delegate void GetMessageDelegate<T>(T str1);
|
|
|
|
public event GetMessageDelegate<string> GetMessageEvent;
|
|
|
|
public SocketServerManager(string ip,int port)
|
|
{
|
|
this.ip = ip;
|
|
this.port = port;
|
|
}
|
|
|
|
public bool ListerSocket()
|
|
{
|
|
try
|
|
{
|
|
socketWatch = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp);
|
|
IPEndPoint endPoint = new IPEndPoint(IPAddress.Parse(ip), port);
|
|
socketWatch.Bind(endPoint);
|
|
socketWatch.Listen(20);
|
|
threadWatch = new Thread(GetMessage);
|
|
threadWatch.Start();
|
|
}
|
|
catch (Exception)
|
|
{
|
|
return false;
|
|
}
|
|
return true;
|
|
}
|
|
|
|
public void SendMessage(string message)
|
|
{
|
|
byte[] arrSendMsg = Encoding.UTF8.GetBytes(message);
|
|
//向客户端发送字节数组信息
|
|
acceptSocket.Send(arrSendMsg);
|
|
}
|
|
|
|
private void GetMessage()
|
|
{
|
|
while (true)
|
|
{
|
|
acceptSocket = socketWatch.Accept();
|
|
Thread th = new Thread(() =>
|
|
{
|
|
while (true)
|
|
{
|
|
byte[] arrServerRecMsg = new byte[1024];
|
|
int length = acceptSocket.Receive(arrServerRecMsg);
|
|
string strSRecMsg = Encoding.UTF8.GetString(arrServerRecMsg, 0, length);
|
|
if (strSRecMsg.Length > 0)
|
|
{
|
|
if(null!=GetMessageEvent)
|
|
GetMessageEvent(strSRecMsg);
|
|
}
|
|
}
|
|
});
|
|
th.IsBackground = true;
|
|
th.Start();
|
|
}
|
|
}
|
|
|
|
}
|
|
}
|