我想在c#中创建一个tcp服务器并在基于通用应用程序javascript的项目中使用它,我创建了以下代码(服务器):
//C# Windows Runtime Component
public sealed class Server
{
public Server()
{
Debug.WriteLine("Server...");
}
public async void Connection()
{
IPAddress ip = IPAddress.Parse("192.168.0.10");
TcpListener server = new TcpListener(ip, portNumber);
TcpClient client = default(TcpClient);
try
{
server.Start();
Debug.WriteLine("Server started ... " + ip.ToString());
}
catch (Exception e)
{
Debug.WriteLine(e.ToString());
}
while (true)
{
client = await server.AcceptTcpClientAsync();
byte[] recievedBuffer = new byte[100];
NetworkStream stream = client.GetStream();
stream.Read(recievedBuffer, 0, recievedBuffer.Length);
string msg = Encoding.UTF8.GetString(recievedBuffer, 0, recievedBuffer.Length);
Debug.WriteLine(msg);
}
}
}
//in HTML
<script>
console.log("test");
var server = new Server.Server();
server.connection();
console.log("msg");
</script>
我不知道为什么Debug.WriteLine和console.log方法不起作用,输出或javascript控制台中都没有打印。
服务器代码适用于Android客户端,如果服务器是“Console App”项目,但在“Universal App Javscript”中没有附加,我没有警告或错误。 所以我不知道我做得不好,因为console.log和Debug.WriteLine不起作用。
答案 0 :(得分:0)
我有一个与windows通用应用程序一起使用的解决方案,我删除了Connection并添加了以下方法:
public async void StartServer()
{
try
{
var streamSocketListener = new Windows.Networking.Sockets.StreamSocketListener();
streamSocketListener.ConnectionReceived += this.StreamSocketListener_ConnectionReceived;
await streamSocketListener.BindEndpointAsync(new HostName("192.168.0.10"), PortNumber);
}
catch (Exception ex){}
}
private async void StreamSocketListener_ConnectionReceived(Windows.Networking.Sockets.StreamSocketListener sender, Windows.Networking.Sockets.StreamSocketListenerConnectionReceivedEventArgs args)
{
string request;
using (var streamReader = new StreamReader(args.Socket.InputStream.AsStreamForRead()))
{
request = await streamReader.ReadLineAsync();
}
sender.Dispose();
}
//in main.js just call this method
new Server.Server().startServer();
但我仍然不知道为什么c#中的Debug.WriteLine()和javascript中的console.log()不能正常工作。