【发布时间】:2018-11-14 08:03:22
【问题描述】:
在此问题的答案中:Server Client Application with .NET and Xamarin 回答的人说:“在 Xamarin.Android 上,您可以使用所有常规的 .Net 套接字类” 我尝试使用 Microsoft 文档示例中的代码,但没有出现任何错误,但应用程序只是在手机上显示:
如果我删除套接字代码,它会正常显示页面。我的代码后面:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using Xamarin.Forms;
using Xamarin.Forms.Xaml;
using System.Net;
using System.Net.Sockets;
namespace App14
{
[XamlCompilation(XamlCompilationOptions.Compile)]
public partial class Page2 : ContentPage
{
public static string data = null;
public static void StartListening()
{
// Data buffer for incoming data.
byte[] bytes = new Byte[1024];
// Establish the local endpoint for the socket.
// Dns.GetHostName returns the name of the
// host running the application.
IPHostEntry ipHostInfo = Dns.GetHostEntry(Dns.GetHostName());
IPAddress ipAddress = ipHostInfo.AddressList[0];
IPEndPoint localEndPoint = new IPEndPoint(ipAddress, 11000);
// Create a TCP/IP socket.
Socket listener = new Socket(ipAddress.AddressFamily,
SocketType.Stream, ProtocolType.Tcp);
try
{
listener.Bind(localEndPoint);
listener.Listen(10);
// Start listening for connections.
while (true)
{
var label = new Label() { Text = "searching for a connection" };
// Program is suspended while waiting for an incoming connection.
Socket handler = listener.Accept();
label.Text = "Found a Connection";
data = null;
// An incoming connection needs to be processed.
while (true)
{
int bytesRec = handler.Receive(bytes);
data += Encoding.ASCII.GetString(bytes, 0, bytesRec);
if (data.IndexOf("<EOF>") > -1)
{
break;
}
}
// Show the data on the console.
label.Text = "Text received" + data;
// Echo the data back to the client.
byte[] msg = Encoding.ASCII.GetBytes(data);
handler.Send(msg);
handler.Shutdown(SocketShutdown.Both);
handler.Close();
}
}
catch (Exception e)
{
Console.WriteLine(e.ToString());
}
}
public Page2 ()
{
StartListening();
Title = "Sign in page";
InitializeComponent();
}
private void page2_click(object sender,EventArgs e)
{
Navigation.PushAsync(new Page1(), true);
}
}
}
为什么会这样?您能否提供一个客户端移动或服务器移动套接字的示例
【问题讨论】:
-
您在 UI/主线程上调用
StartListening并因此阻塞它。查看 Task.Run 作为将套接字侦听器例程放在不同线程上的一种方式:msdn.microsoft.com/en-us/library/hh195051(v=vs.110).aspx