Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- 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.Net;
- using System.IO;
- using System.ComponentModel;
- using System.Threading;
- namespace xamarinTcpIP
- {
- [Activity(Label = "xamarinTcpIP", MainLauncher = true, Icon = "@drawable/icon")]
- public class MainActivity : Activity
- {
- public Button buttonConnect;
- public Button buttonSend;
- public TextView textviewConversation; //textView_Conversation
- public EditText editTextMessage;
- private TcpClient client;
- private StreamReader STR;
- private StreamWriter STW;
- private string received;
- private String text_to_send;
- public BackgroundWorker worker1;
- public BackgroundWorker worker2;
- protected override void OnCreate(Bundle bundle)
- {
- base.OnCreate(bundle);
- SetContentView(Resource.Layout.Main);
- ///// <- old
- buttonConnect = FindViewById<Button>(Resource.Id.button_Connect);
- buttonSend = FindViewById<Button>(Resource.Id.button_Send);
- textviewConversation = FindViewById<TextView>(Resource.Id.textView_Conversation);
- editTextMessage = FindViewById<EditText> (Resource.Id.editText_Message);
- buttonConnect.Click += buttonClickConnect;
- buttonSend.Click += buttonClickSend;
- worker1 = new BackgroundWorker();
- worker1.DoWork += backgroundWorker1_DoWork;
- worker2 = new BackgroundWorker();
- worker2.DoWork += backgroundWorker2_DoWork;
- }
- private void backgroundWorker1_DoWork(object sender, DoWorkEventArgs e) //receiving message
- {
- while (client.Connected)
- {
- try
- {
- received = STR.ReadLine();
- textviewConversation.Text += "->: " + received + "\n";
- }
- catch (Exception ex)
- {
- Console.WriteLine(ex.Message);
- }
- }
- }
- private void backgroundWorker2_DoWork(object sender, DoWorkEventArgs e) //sending message
- {
- if (client.Connected)
- {
- STW.WriteLine(text_to_send);
- }
- else
- {
- Console.WriteLine("send failed !");
- }
- worker2.CancelAsync();
- }
- private void buttonClickConnect(object sender, EventArgs e)
- {
- client = new TcpClient();
- IPEndPoint IP_End = new IPEndPoint(IPAddress.Parse("192.168.1.1"), int.Parse("13000"));
- try
- {
- client.Connect(IP_End);
- if (client.Connected)
- {
- textviewConversation.Text += "Connected to server" + "\n";
- STR = new StreamReader(client.GetStream());
- STW = new StreamWriter(client.GetStream());
- STW.AutoFlush = true;
- worker1.RunWorkerAsync();
- worker2.WorkerSupportsCancellation = true;
- }
- }
- catch (Exception ex)
- {
- Console.WriteLine(ex.Message);
- }
- }
- private void buttonClickSend(object sender, EventArgs e)
- {
- if (editTextMessage.Text != "")
- {
- text_to_send = editTextMessage.Text;
- worker2.RunWorkerAsync();
- }
- editTextMessage.Text = "";
- }
- }
- }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement