Как отправить значения через сокет - PullRequest
0 голосов
/ 17 апреля 2020

Я хочу отправить значение с одного устройства на другое устройство через WiFi с помощью сокета.

Я поместил следующий код для передачи значений на различные устройства и с них и перестал работать.

полный код.

привет

Я хочу отправить значение с одного устройства на другое устройство через WiFi с помощью сокета.

Я поместил следующий код для передачи значений И с разных устройств и перестаньте работать.

полный код.

using Android.App;
using Android.OS;
using Android.Support.V7.App;
using Android.Runtime;
using Android.Widget;
using System.Net.Sockets;
using System;
using System.Text;
using System.Threading;
using System.Net;

namespace TCP_CONNECT
{
[Activity(Label = "@string/app_name", Theme = "@style/AppTheme", MainLauncher = true)]
public class MainActivity : AppCompatActivity
{
int i;
TcpClient client; // Creates a TCP Client
NetworkStream stream; //Creats a NetworkStream (used for sending and receiving data)
byte[] datalength = new byte[4]; // creates a new byte with length 4 ( used for receivng data's lenght)
Button buttonConnect;// = FindViewById(Resource.Id._buttonConnect);
Button buttonSend;// = FindViewById(Resource.Id._buttonSend);
EditText etextSend;// = FindViewById(Resource.Id._etextSend);
TextView textReceive;
TextView textip;
EditText textedid;
string ipString;
// Global Values }
protected override void OnCreate(Bundle savedInstanceState)
{
base.OnCreate(savedInstanceState);
Xamarin.Essentials.Platform.Init(this, savedInstanceState);
// Set our view from the "main" layout resource
SetContentView(Resource.Layout.activity_main);
ip();

        var textip= FindViewById<TextView>(Resource.Id.textView1);
        textip.Text = ipString;

        buttonConnect = FindViewById<Button>(Resource.Id._buttonConnect);
        buttonSend = FindViewById<Button>(Resource.Id._buttonSend);
        etextSend = FindViewById<EditText>(Resource.Id.etextSend);
        textReceive = FindViewById<TextView>(Resource.Id.textviewReceive);

        textedid = FindViewById<EditText>(Resource.Id.textInputEditText1);
        //buttonSend.Enabled = false;
        // UI init }
        buttonConnect.Click += buttonConnect_Click;
        buttonSend.Click += buttonSend_Click;
        //ThreadPool.QueueUserWorkItem(o => receiveData());
    }
    void buttonConnect_Click(object sender, EventArgs e)
    {
        try
        {
            if (buttonConnect.Text == "Connect")
            {
                client = new TcpClient(textedid.Text, 1433); //Trys to Connect
                Toast.MakeText(this, "Connected", ToastLength.Short).Show();
                buttonConnect.Text = "Dis-Connect";
                textReceive.Text = null;
                buttonSend.Enabled = true;
                clientReceive(); //Starts Receiving When Connected
            }
            else
            {
                buttonConnect.Text = "Connect";
                Toast.MakeText(this, "Dis-Connected", ToastLength.Short).Show();
                client.GetStream().Close();
                client.Close();
            }
        }
        catch (Exception ex)
        {
            Toast.MakeText(this, ex.Message, ToastLength.Short).Show();
        }
    }

    private void clientReceive()
    {
        try
        {
            stream = client.GetStream(); //Gets The Stream of The Connection
            new Thread(() => // Thread (like Timer)
            {
                while ((i = stream.Read(datalength, 0, 4)) != 0)//Keeps Trying to Receive the Size of the Message or Data
                {
                    // how to make a byte E.X byte[] examlpe = new byte[the size of the byte here] , i used BitConverter.ToInt32(datalength,0) cuz i received the length of the data in byte called datalength :D
                    byte[] data = new byte[BitConverter.ToInt32(datalength, 0)]; // Creates a Byte for the data to be Received On
                    stream.Read(data, 0, data.Length); //Receives The Real Data not the Size
                    this.RunOnUiThread(() => this.textReceive.Text = textReceive.Text + (Encoding.ASCII.GetString(data)) +
                               System.Environment.NewLine);
                }
            }).Start(); // Start the Thread
        }
        catch (Exception ex)
        {
            Toast.MakeText(this, ex.Message, ToastLength.Short).Show();
        }
    }

    void buttonSend_Click(object sender, EventArgs e)
    {
        try
        {
            if (client.Connected) // if the client is connected
            {
                clientSend(this.etextSend.Text); // uses the Function ClientSend and the msg as txtSend.Text
            }
        }
        catch (Exception ex)
        {
            Toast.MakeText(this, ex.Message, ToastLength.Short).Show();
        }
    }

    public void clientSend(string msg)
    {
        try
        {
            stream = client.GetStream(); //Gets The Stream of The Connection
            byte[] data; // creates a new byte without mentioning the size of it cuz its a byte used for sending
            data = Encoding.Default.GetBytes(msg); // put the msg in the byte ( it automaticly uses the size of the msg )
            int length = data.Length; // Gets the length of the byte data
            byte[] datalength = new byte[4]; // Creates a new byte with length of 4
            datalength = BitConverter.GetBytes(length); //put the length in a byte to send it
            stream.Write(datalength, 0, 4); // sends the data's length
            stream.Write(data, 0, data.Length); //Sends the real data
        }
        catch (Exception ex)
        {
            Toast.MakeText(this, ex.Message, ToastLength.Short).Show();
        }
    }

    void ip()
    {
        IPAddress[] localIp = Dns.GetHostAddresses(Dns.GetHostName());
        foreach (IPAddress address in localIp)
        {
            if (address.AddressFamily == AddressFamily.InterNetwork)
            {
                ipString = address.ToString();
            }
        }
    }
    public override void OnRequestPermissionsResult(int requestCode, string[] permissions, [GeneratedEnum] Android.Content.PM.Permission[] grantResults)
    {
        Xamarin.Essentials.Platform.OnRequestPermissionsResult(requestCode, permissions, grantResults);

        base.OnRequestPermissionsResult(requestCode, permissions, grantResults);
    }
}
}

...