【发布时间】:2016-01-07 17:51:13
【问题描述】:
我相信我要创建的是一个侦听特定端口的服务,当数据发送到该端口时,它会将数据发送到另一个脚本进行处理。
但由于某种原因,当我尝试启动该服务时它会超时。我的日志告诉我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
{
}
}
【问题讨论】:
-
我假设您的意思是 Windows 服务。你的
OnStart()方法是什么样的? -
提示:制作 Windows 服务(并测试它们)的一种简单方法是使用TopShelf - on Nuget。它为您提供了一个简单的 exe,您可以在命令行运行或作为服务安装和运行。
标签: c# service tcp windows-services server