你好,我试图在一台机器上制作两个程序(服务器和客户端)。我用WPF做到了,然后尝试用UWP做到了,但没有成功。问题在于服务器中的侦听器正在等待连接,但是它永远不会来。仅当我尝试从两个单独的项目进行连接时,才会发生这种情况。
如果我在一个项目中这样做,一切都会很好。我在某处看到无法使用UWP在一台计算机上运行服务器和客户端,但是对信息的解释不是很好。
所以我的问题是,是否可以在一台计算机上用UWP为服务器和客户端创建两个单独的项目,如果不能,我该如何测试程序(我需要另一台计算机来测试它还是有其他方法可以完成)? 。
有人可以告诉我是否有一种可能的方式来发布我的项目,例如“控制台应用程序”中的选项,以便我可以将客户端发送到另一台计算机,然后尝试。我在互联网上能找到的就是如何将您的应用发布到Microsoft Store。
服务器
public sealed partial class MainPage : Page
{
string port = "11000";
string hostv4 = "127.0.0.1";
StreamSocketListener server;
public MainPage()
{
InitializeComponent();
StartServer();
}
private async void StartServer()
{
HostName name = new HostName(hostv4);
server = new StreamSocketListener();
server.ConnectionReceived += this.Receive;
await server.BindEndpointAsync(name, port);
Chat.Content += ("server is listening...\n");//chat is a ScrollViewer where I show the received messsges
}
private async void Receive(StreamSocketListener sender, StreamSocketListenerConnectionReceivedEventArgs args)
{
string receivedMsg;
using (var sr = new StreamReader(args.Socket.InputStream.AsStreamForRead()))
{
receivedMsg = await sr.ReadLineAsync();
}
await this.Dispatcher.RunAsync(CoreDispatcherPriority.Normal, () => Chat.Content += (string.Format("server received the request: \"{0}\"\n", receivedMsg)));
}
}
客户端
public sealed partial class MainPage : Page
{
string port = "11000";
string hostv4 = "127.0.0.1";
StreamSocket client;
public MainPage()
{
this.InitializeComponent();
Connect();
}
private async void Connect()
{
client = new StreamSocket();
HostName name = new HostName(hostv4);
await this.Dispatcher.RunAsync(CoreDispatcherPriority.Normal, () => Chat.Content += (string.Format("client trying to connect...\n")));
await client.ConnectAsync(name, port);
await this.Dispatcher.RunAsync(CoreDispatcherPriority.Normal, () => Chat.Content += (string.Format("client connected\n")));
}
private async void Button_Click(object sender, RoutedEventArgs e)
{
string request = Input.Text; //Input is the name of my TextBox
using (Stream outputStream = client.OutputStream.AsStreamForWrite())
{
using (var sw = new StreamWriter(outputStream))
{
await sw.WriteLineAsync(request);
await sw.FlushAsync();
}
}
await this.Dispatcher.RunAsync(CoreDispatcherPriority.Normal, () => Chat.Content += (string.Format("client sent request: {0}\n", request)));
}
我还从功能中启用了Internet(客户端和服务器)和专用网络(客户端和服务器)