使用套接字在移动设备和PC之间建立Internet连接

时间:2017-10-09 19:33:49

标签: c# android sockets xamarin

我尝试使用C#中的套接字在移动(客户端)和PC(服务器)之间建立互联网连接。它只是发送文本字符串,没有什么大的但它不起作用。相同的客户端代码适用于PC。任何提示或建议我如何实现它?

客户端:

using System;
using Android.App;
using Android.Content;
using Android.Runtime;
using Android.Views;
using Android.Widget;
using Android.OS;
using System.Net.Sockets;
using System.Text;

namespace ClientPhone
{
    [Activity(Label = "ClientPhone", MainLauncher = true, Icon = "@drawable/icon")]
    public class MainActivity : Activity
    {       
        protected override void OnCreate(Bundle bundle)
        {
            base.OnCreate(bundle);

            SetContentView(Resource.Layout.Main);

            Button button = FindViewById<Button>(Resource.Id.MyButton);
            button.Click += delegate { Connect(); };
        }

        public void Connect()
        {
            Socket clientSocket = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.IP);
            TextView stateTextView = FindViewById<TextView>(Resource.Id.stateTextView);
            stateTextView.Text = "Clicked";
            try
            {
                clientSocket.Connect("MyIp", 5000);

                stateTextView.Text = "Connected";
                clientSocket.Send(ASCIIEncoding.ASCII.GetBytes("Hello world phone"));
            }
            catch (SocketException e)
            {
                stateTextView.Text = "Couldn't connect";
            }
        }
    }
}

服务器:

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Net.Sockets;
using System.Net;

namespace Server
{
    class Program
    {
        static void Main(string[] args)
        {
            Socket serverSocket = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.IP);
            byte[] recieveBuffor = new byte[256];
            serverSocket.Bind(new IPEndPoint(IPAddress.Parse("MyIp"),5000));
            serverSocket.Listen(1);
            Socket client = serverSocket.Accept();
            client.Receive(recieveBuffor);
            Console.WriteLine(ASCIIEncoding.ASCII.GetString(recieveBuffor));
        }
    }
}

当然,我在Android清单属性中标记了 Internet 。当手机在移动互联网上并通过我的电脑使用WiFi广播(当他们在本地时)时,我也尝试连接。当我调试手机应用程序时,它会在clientSocket.Connect("MyIp", 5000)停止,然后在几秒钟后它会抛出一个套接字异常。

0 个答案:

没有答案