我正在设置Windows服务,该服务仅打开UDP端口并将收到的任何内容打印到日志文件中。但是我的问题是,当服务打开端口时,我什么也收不到。我正在从UDP发送方android应用发送UDP数据包。发送数据包的电话在我的家庭Wi-fi网络上(以及运行该服务的PC上)。服务名称是myShutdownService。我尝试停止并再次启动服务,但这没有帮助。
Service.cs代码:
namespace myShutdownService
{
public partial class Service1 : ServiceBase
{
public Service1()
{
InitializeComponent();
UDPSocket s = new UDPSocket();
string ip = UDPSocket.GetLocalIPAddress();
int port = 2700;
s.Server(ip, port);
s.WriteToFile("Opening server socket on " + ip + ":" + port );
}
protected override void OnStart(string[] args)
{
}
protected override void OnStop()
{
UDPSocket s = new UDPSocket();
s.WriteToFile(" STOPPING SERVICE");
}
}
}
我的UDP套接字类:
namespace myShutdownService
{
public class UDPSocket
{
private Socket _socket = new Socket(AddressFamily.InterNetwork, SocketType.Dgram, ProtocolType.Udp);
private const int bufSize = 8 * 1024;
private State state = new State();
private EndPoint epFrom = new IPEndPoint(IPAddress.Any, 0);
private AsyncCallback recv = null;
public class State
{
public byte[] buffer = new byte[bufSize];
}
public static string GetLocalIPAddress()
{
var host = Dns.GetHostEntry(Dns.GetHostName());
foreach (var ip in host.AddressList)
{
if (ip.AddressFamily == AddressFamily.InterNetwork)
{
return ip.ToString();
}
}
throw new Exception("No network adapters with an IPv4 address in the system!");
}
public void Server(string address, int port)
{
_socket.SetSocketOption(SocketOptionLevel.IP, SocketOptionName.ReuseAddress, true);
_socket.Bind(new IPEndPoint(IPAddress.Parse(address), port));
Receive();
}
public void Client(string address, int port)
{
_socket.Connect(IPAddress.Parse(address), port);
Receive();
}
public void Send(string text)
{
byte[] data = Encoding.ASCII.GetBytes(text);
_socket.BeginSend(data, 0, data.Length, SocketFlags.None, (ar) =>
{
State so = (State)ar.AsyncState;
int bytes = _socket.EndSend(ar);
WriteToFile("SEND: " + text);
}, state);
}
private void Receive()
{
_socket.BeginReceiveFrom(state.buffer, 0, bufSize, SocketFlags.None, ref epFrom, recv = (ar) =>
{
State so = (State)ar.AsyncState;
int bytes = _socket.EndReceiveFrom(ar, ref epFrom);
_socket.BeginReceiveFrom(so.buffer, 0, bufSize, SocketFlags.None, ref epFrom, recv, so);
WriteToFile("RECV: " + epFrom.ToString() + " message: " + Encoding.ASCII.GetString(so.buffer, 0, bytes));
}, state);
}
public void WriteToFile(string Message)
{
string path = AppDomain.CurrentDomain.BaseDirectory + "\\Logs";
if (!Directory.Exists(path))
{
Directory.CreateDirectory(path);
}
string filepath = AppDomain.CurrentDomain.BaseDirectory + "\\Logs\\ServiceLog_" + DateTime.Now.Date.ToShortDateString().Replace('/', '_') + ".txt";
if (!File.Exists(filepath))
{
// Create a file to write to.
using (StreamWriter sw = File.CreateText(filepath))
{
sw.WriteLine(Message);
}
}
else
{
using (StreamWriter sw = File.AppendText(filepath))
{
sw.WriteLine(Message);
}
}
}
}
}
日志文件输出:
Opening server socket on 192.168.56.1:2700
STOPPING SERVICE
Opening server socket on 192.168.56.1:2700