Pil*_*ren 2 c# windows-services installutil tcplistener tcpclient
我正在尝试创建一个需要在后台运行并侦听传入流量的 Windows 服务(正常和常规的 TCP 侦听器)
我的代码是:
private TcpListener server;
public void startServer()
{
// EventLog.WriteEntry(source, "connected on: " + ipAddress.ToString() + " port: " + Service1.Port.ToString());
server = new TcpListener(IPAddress.Parse("127.0.0.1"), Service1.Port);
server.Start();
while (true)
{
var client = server.AcceptTcpClient();
new Thread(work).Start(client);
}
public void work(object client)
{
string msg = null;
var clientLocal = (TcpClient)client;
using (NetworkStream ns = clientLocal.GetStream())
using (StreamReader sr = new StreamReader(ns))
{
byte[] msgFullArray = new UTF8Encoding(true).GetBytes(msg);
fs.Write(msgFullArray, 0, msg.Length);
}
Run Code Online (Sandbox Code Playgroud)
现在,如果您根本不看工作方法,因为每当我启动我的服务时,每当我尝试在我的服务中启动它时它都会冻结:
var client = server.AcceptTcpClient();
Run Code Online (Sandbox Code Playgroud)
这意味着我的服务永远不会使用 Thread 或我的 Work 方法..我可以从以前的日志中看到它进入我的 while 循环然后只是超时服务
小智 5
在您的OnStart方法中,您必须实例化一个服务器类。
protected override void OnStart(string[] args)
{
// Create the Server Object ans Start it.
server = new TCPServer();
server.StartServer();
}
Run Code Online (Sandbox Code Playgroud)
负责通过创建一个新的Thread(因此它是一个非阻塞进程)来处理与服务器的连接
public void StartServer()
{
if (m_server!=null)
{
// Create a ArrayList for storing SocketListeners before
// starting the server.
m_socketListenersList = new ArrayList();
// Start the Server and start the thread to listen client
// requests.
m_server.Start();
m_serverThread = new Thread(new ThreadStart(ServerThreadStart));
m_serverThread.Start();
// Create a low priority thread that checks and deletes client
// SocktConnection objcts that are marked for deletion.
m_purgingThread = new Thread(new ThreadStart(PurgingThreadStart));
m_purgingThread.Priority=ThreadPriority.Lowest;
m_purgingThread.Start();
}
}
Run Code Online (Sandbox Code Playgroud)
对于每个套接字,它将被一个TCPListener.
private void ServerThreadStart()
{
// Client Socket variable;
Socket clientSocket = null;
TCPSocketListener socketListener = null;
while(!m_stopServer)
{
try
{
// Wait for any client requests and if there is any
// request from any client accept it (Wait indefinitely).
clientSocket = m_server.AcceptSocket();
// Create a SocketListener object for the client.
socketListener = new TCPSocketListener(clientSocket);
// Add the socket listener to an array list in a thread
// safe fashon.
//Monitor.Enter(m_socketListenersList);
lock(m_socketListenersList)
{
m_socketListenersList.Add(socketListener);
}
//Monitor.Exit(m_socketListenersList);
// Start a communicating with the client in a different
// thread.
socketListener.StartSocketListener();
}
catch (SocketException se)
{
m_stopServer = true;
}
}
}
Run Code Online (Sandbox Code Playgroud)
这是完整的项目文章。
| 归档时间: |
|
| 查看次数: |
18012 次 |
| 最近记录: |