我相信我想要创建的是一个监听特定端口的服务,当数据发送到该端口时,它会将数据发送到另一个脚本进行处理。
由于某种原因,当我尝试启动该服务时,该服务超时了。我的日志告诉我 TcpClient client = server.AcceptTcpClient();
是它停止的地方(实际上,它卡在服务中的“启动”位置)。
由于我没有使用 C#、制作服务或以这种方式使用服务器的经验,因此代码几乎就是我在网上找到的。
OnStart 方法如下所示。
protected override void OnStart(string[] args)
{
try
{
TcpListener server = null;
// Set the TcpListener on port 13000.
Int32 port = 1234;
IPAddress localAddr = IPAddress.Parse("127.0.0.1");
// TcpListener server = new TcpListener(port);
server = new TcpListener(localAddr, port);
// Start listening for client requests.
server.Start();
// Buffer for reading data
Byte[] bytes = new Byte[256];
String data = null;
// Enter the listening loop.
while (true)
{
// Perform a blocking call to accept requests.
// You could also user server.AcceptSocket() here.
TcpClient client = server.AcceptTcpClient();
data = null;
// Get a stream object for reading and writing
NetworkStream stream = client.GetStream();
int i;
// Loop to receive all the data sent by the client.
while ((i = stream.Read(bytes, 0, bytes.Length)) != 0)
{
// Translate data bytes to a ASCII string.
data = System.Text.Encoding.ASCII.GetString(bytes, 0, i);
// Process the data sent by the client.
data = data.ToUpper();
byte[] msg = System.Text.Encoding.ASCII.GetBytes(data);
// Send back a response.
stream.Write(msg, 0, msg.Length);
}
// Shutdown and end connection
client.Close();
}
}
catch (SocketException e)
{
}
finally
{
}
}
最佳答案
根据MSDN , TcpServer.AcceptTcpClient 会阻塞,因此您可能永远不会从 Service 的 OnStart 方法返回,这会导致服务永远不会真正“启动”。
您可以考虑使用另一个线程并尽快从 OnStart 返回。
干杯
关于C# 监听端口的服务,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/33044052/