windows form app sending strings - c#

I made a tcp/ip chat windows form application and it works just fine but I want to make the application to send the text automatically I don't want the user to click the send button like a live streaming!
and I am using Asynchronous connection.
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;
using System.Net;
using System.Net.Sockets;
namespace Chat
{
public partial class Form1 : Form
{
Socket sck;
EndPoint epLocal, epRemote;
public Form1()
{
InitializeComponent();
sck = new Socket(AddressFamily.InterNetwork, SocketType.Dgram, ProtocolType.Udp);
sck.SetSocketOption(SocketOptionLevel.Socket, SocketOptionName.ReuseAddress, true);
textBox1.Text = GetLocalIP();//this is where the application is running IP address
//textBox5.Text = GetLocalIP();
}
private string GetLocalIP()
{
IPHostEntry host;
host = Dns.GetHostEntry(Dns.GetHostName());
foreach (IPAddress ip in host.AddressList)
{
if(ip.AddressFamily == AddressFamily.InterNetwork)
{
return ip.ToString();
}
}
return "127.0.0.1"; //here we put the android device's IP
}
private void MessageCallBack(IAsyncResult aResult)
{
try {
int size = sck.EndReceiveFrom(aResult, ref epRemote);
if(size>0)
{
byte[] receivedData = new byte[1464];
receivedData = (byte[])aResult.AsyncState;
ASCIIEncoding eEncoding = new ASCIIEncoding();
string receivedMessage = eEncoding.GetString(receivedData);
//b3deen bntba3 el msg bs b7aletna bdna n5li el touch active.
listBox1.Items.Add("Sender:" + receivedMessage);
}
byte[] buffer = new byte[1500];
sck.BeginReceiveFrom(buffer, 0, buffer.Length, SocketFlags.None, ref epRemote, new AsyncCallback(MessageCallBack), buffer);
}
catch (Exception exp)
{
MessageBox.Show(exp.ToString());
}
}
private void button1_Click(object sender, EventArgs e)
{
try
{
//binding the message
epLocal = new IPEndPoint(IPAddress.Parse("192.168.1.9"), Convert.ToInt32("80"));
sck.Bind(epLocal);
//hoon el address ta3 el mobile
epRemote = new IPEndPoint(IPAddress.Parse("192.168.1.9"), Convert.ToInt32("81"));//texbox5 bn7at el ip ta3 el android wl txt el tani ta3 le port
//hoon bn3ml connect network
sck.Connect(epRemote);
byte[] buffer = new byte[1500];
sck.BeginReceiveFrom(buffer, 0, buffer.Length, SocketFlags.None, ref epRemote, new AsyncCallback(MessageCallBack), buffer);
button1.Text = "Connected";
button1.Enabled = false;
button2.Enabled = true;
textBox3.Focus();
//trying to live sending
}
catch (Exception exp)
{
MessageBox.Show(exp.ToString());
}
}
private void button2_Click(object sender, EventArgs e)
{
try
{
System.Text.ASCIIEncoding enc = new System.Text.ASCIIEncoding();
byte[] msg = new byte[1500];
msg = enc.GetBytes(textBox3.Text);
sck.Send(msg);
listBox1.Items.Add("YOU:" + textBox3.Text);
}catch (Exception exp)
{
MessageBox.Show(exp.ToString());
}
// Close();
}
}
}

I assume that you want to send the text the user entered as he finished to type it. Even if I'd say this is a bad idea because it will confuse your users, you could add a timer which is counting the time since the user's last key stroke and if a given time was passed (let's say 5 secs), it invokes the method your button click is invoking as well to send the string.

Hey all I just find out what to do I wanted to send each string when its written so what i did I just handled the event for the textbox it self so when ever its changed it will send it right away :D good luck all :)

Related

TCP/IP Using BeginReceive in a Loop

I am currently trying to make a chess application with two clients and one server, lets say client1 and client2 are trying to speak to each other. the server side is ok but the client side is a little corrupted. The application has a chat part and when client1 wants to speak client2, client2 should receive the message immediately. When i put the BeginReceive line in a loop, client2 receives at the moment the message is sent but then connection problem occurs. If i dont make a loop with BeginReceive, then application has no errors but when client1 sends the message, client2 doesnt see the message immediately. Only when, client2 sends a message to client1, client1's first message is seen in the chat. can you help me about it?
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;
using System.Net;
using System.Net.Sockets;
namespace ChessClient
{
public partial class Form1 : Form
{
private Socket client;
private byte[] data = new byte[1024];
private int size = 1024;
public Form1()
{
InitializeComponent();
sendbtn.Click += new EventHandler(ButtonSendOnClick);
connectbtn.Click += new EventHandler(ButtonConnectOnClick);
disconnectbtn.Click += new EventHandler(ButtonDisconOnClick);
}
void ButtonConnectOnClick(object obj, EventArgs ea)
{
conStatus.Text = "Connecting...";
Socket newsock = new Socket(AddressFamily.InterNetwork,
SocketType.Stream, ProtocolType.Tcp);
IPEndPoint iep = new IPEndPoint(IPAddress.Parse("127.0.0.1"), 9060);
newsock.BeginConnect(iep, new AsyncCallback(Connected), newsock);
}
void ButtonSendOnClick(object obj, EventArgs ea)
{
byte[] message = Encoding.ASCII.GetBytes(chat.Text);
chat.Clear();
client.BeginSend(message, 0, message.Length, SocketFlags.None,
new AsyncCallback(SendData), client);
}
void ButtonDisconOnClick(object obj, EventArgs ea)
{
client.Close();
conStatus.Text = "Disconnected";
}
void Connected(IAsyncResult iar)
{
client = (Socket)iar.AsyncState;
try
{
client.EndConnect(iar);
conStatus.Text = "Connected to: " + client.RemoteEndPoint.ToString();
This is where i put inside the loop, beginreceive was in an infinite loop
client.BeginReceive(data, 0, size, SocketFlags.None,
new AsyncCallback(ReceiveData), client);
}
catch (SocketException)
{
conStatus.Text = "Error connecting";
}
}
void ReceiveData(IAsyncResult iar)
{
Socket remote = (Socket)iar.AsyncState;
int recv = remote.EndReceive(iar);
string stringData = Encoding.ASCII.GetString(data, 0, recv);
chatBox.Items.Add(stringData);
}
void SendData(IAsyncResult iar)
{
Socket remote = (Socket)iar.AsyncState;
remote.EndSend(iar);
remote.BeginReceive(data, 0, size, SocketFlags.None,
new AsyncCallback(ReceiveData), remote);
}
}
}

Adding Security To Chat Client

So this is my basic chat program which allows user to add its own IP and receive an IP, plus custom ports to communicate.
In the windows forms design I have:
Textbox --- textLocalIp
Textbox --- textLocalPort
Textbox --- textFriendIp
Textbox --- textFriendPort
Textbox --- textMessage
Listbox --- listMessage
Button --- Start
Button --- Send
So this is a very basic client but what I want help with is making it secure/more secure because security right now is not good.
Maybe like a tunnel with different IP's so that you don't have to know the receivers IP, just a IP they provide which then sends it to them or whatever?
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;
using System.Net;
using System.Net.Sockets;
namespace Client
{
public partial class Form1 : Form
{
Socket sck;
EndPoint epLocal, epRemote;
public Form1()
{
InitializeComponent();
sck = new Socket(AddressFamily.InterNetwork, SocketType.Dgram, ProtocolType.Udp);
sck.SetSocketOption(SocketOptionLevel.Socket, SocketOptionName.ReuseAddress, true);
textLocalIp.Text = GetLocalIP();
textFriendIp.Text = GetLocalIP();
}
private string GetLocalIP()
{
IPHostEntry host;
host = Dns.GetHostEntry(Dns.GetHostName());
foreach (IPAddress ip in host.AddressList)
{
if (ip.AddressFamily == AddressFamily.InterNetwork)
{
return ip.ToString();
}
}
return "127.0.0.1";
}
private void MessageCallBack(IAsyncResult aResult)
{
try
{
int size = sck.EndReceiveFrom(aResult, ref epRemote);
if (size > 0)
{
byte[] recievedData = new byte[1464];
recievedData = (byte[])aResult.AsyncState;
ASCIIEncoding eEncoding = new ASCIIEncoding();
string receivedMessage = eEncoding.GetString(recievedData);
listMessage.Items.Add("Sender: "+receivedMessage);
}
byte[] buffer = new byte[1500];
sck.BeginReceiveFrom(buffer, 0, buffer.Length, SocketFlags.None, ref epRemote, new AsyncCallback(MessageCallBack), buffer);
}
catch (Exception exp)
{
MessageBox.Show(exp.ToString());
}
}
private void button1_Click(object sender, EventArgs e)
{
try
{
System.Text.ASCIIEncoding enc = new System.Text.ASCIIEncoding();
byte[] msg = new byte[1500];
msg = enc.GetBytes(textMessage.Text);
sck.Send(msg);
listMessage.Items.Add("Local:" + textMessage.Text);
textMessage.Clear();
}
catch (Exception ex)
{
MessageBox.Show(ex.ToString());
}
}
private void start_Click(object sender, EventArgs e)
{
try
{
epLocal = new IPEndPoint(IPAddress.Parse(textLocalIp.Text), Convert.ToInt32(textLocalPort.Text));
sck.Bind(epLocal);
epRemote = new IPEndPoint(IPAddress.Parse(textFriendIp.Text), Convert.ToInt32(textFriendPort.Text));
sck.Connect(epRemote);
byte[] buffer = new byte[1500];
sck.BeginReceiveFrom(buffer, 0, buffer.Length, SocketFlags.None, ref epRemote, new AsyncCallback(MessageCallBack), buffer);
start.Text = "Connected";
start.Enabled = false;
send.Enabled = true;
textMessage.Focus();
}
catch (Exception ex)
{
MessageBox.Show(ex.ToString());
}
}
It is more difficult to implement socket communication security using channels. So I suggest you encrypt the IP and transmission content.
For IP encryption, you can set the Passwordchar attribute of the TextBox to *.
For transmission content, you can encrypt it with an encryption algorithm.
The following code implements the communication between a server and multiple clients, and you can perform encryption on this basis.
Server:
namespace Server
{
class Program
{
private static byte[] result = new byte[1024];
private static int myProt = 8885;
static Socket serverSocket;
static void Main(string[] args)
{
serverSocket = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp);
serverSocket.Bind(new IPEndPoint(IPAddress.Any, myProt));
serverSocket.Listen(10); //Set up to 10 queued connection requests
Console.WriteLine("Start listening {0} successfully", serverSocket.LocalEndPoint.ToString());
Thread myThread = new Thread(ListenClientConnect);
myThread.Start();
Console.ReadLine();
}
/// <summary>
/// Listen for Client connections
/// </summary>
private static void ListenClientConnect()
{
while (true)
{
Socket clientSocket = serverSocket.Accept();
clientSocket.Send(Encoding.ASCII.GetBytes("Server Say Hello"));
Thread receiveThread = new Thread(ReceiveMessage);
receiveThread.Start(clientSocket);
}
}
/// <summary>
/// receive data
/// </summary>
/// <param name="clientSocket"></param>
private static void ReceiveMessage(object clientSocket)
{
Socket myClientSocket = (Socket)clientSocket;
while (true)
{
try
{
int receiveNumber = myClientSocket.Receive(result);
Console.WriteLine("Receive client {0} message {1}", myClientSocket.RemoteEndPoint.ToString(), Encoding.ASCII.GetString(result, 0, receiveNumber));
}
catch (Exception ex)
{
Console.WriteLine(ex.Message);
myClientSocket.Shutdown(SocketShutdown.Both);
myClientSocket.Close();
break;
}
}
}
}
}
Client:
namespace Client
{
class Program
{
private static byte[] result = new byte[1024];
static void Main(string[] args)
{
IPAddress ip = IPAddress.Parse("127.0.0.1");
Socket clientSocket = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp);
try
{
clientSocket.Connect(new IPEndPoint(ip, 8885));
Console.WriteLine("Successfully connected to the server");
}
catch
{
Console.WriteLine("Failed to connect to the server, please press Enter to exit!");
return;
}
//Receive data through clientSocket
int receiveLength = clientSocket.Receive(result);
Console.WriteLine("Server:{0}", Encoding.ASCII.GetString(result, 0, receiveLength));
//Send data through clientSocket
for (int i = 0; i <3; i++)
{
try
{
Thread.Sleep(1000);
string sendMessage = "client send Message Hellp" + DateTime.Now;
clientSocket.Send(Encoding.ASCII.GetBytes(sendMessage));
Console.WriteLine("Client:{0}" + sendMessage);
}
catch
{
clientSocket.Shutdown(SocketShutdown.Both);
clientSocket.Close();
break;
}
}
Console.WriteLine("After sending, press Enter to exit");
Console.ReadLine();
}
}
}

How to keep telnet port 23 open to keep reading data coming in, in C# windows form

I finally got the program to work as I wanted is reading the data from the telnet port for every scan it triggers, but now the only problem I am getting is that is reading the data if I display it in the console but I need it display into my main display which will be a text box multiline, can you see why I am getting this
using System;
using System.Collections.Generic;
using System.Net.Sockets;
using System.Text;
using System.Threading;
using System.Windows.Forms;
namespace BarcodeReceivingApp
{
public partial class BarcodeReceivingForm : Form
{
public BarcodeReceivingForm()
{
InitializeComponent();
}
private Thread _readWriteThread;
private TcpClient _client;
private NetworkStream _networkStream;
private void btn_ConnectToTelnetPort_Click(object sender, EventArgs e)
{
// connection tcp/ip
const string hostname = "myipaddress";
const int port = 23;
ServerSocket(hostname, port);
//Connect();
}
public void ServerSocket(string ip, int port)
{
try
{
_client = new TcpClient(ip, port);
lbl_ConnectionMessage.Text = #"Connected to server.";
}
catch (SocketException)
{
MessageBox.Show(#"Failed to connect to server");
return;
}
//Assign networkstream
_networkStream = _client.GetStream();
//start socket read/write thread
_readWriteThread = new Thread(ReadWrite);
_readWriteThread.Start();
}
private void ReadWrite()
{
var received = "";
//Read first thing givent o us
received = Read();
//Console.WriteLine(received);
txt_BarcodeDisplay.Text = received + Environment.NewLine;
//txt_BarcodeDisplay.Text = recieved.ToString();
//Set up connection loop
while (true)
{
var command = btn_StopConnection.Text;
if (command == "STOP1")
break;
//write(command);
received = Read();
//Console.WriteLine(received);
txt_BarcodeDisplay.Text += received + Environment.NewLine;
}
// possible method to end the port connection
}
public string Read()
{
byte[] data = new byte[1024];
var received = "";
var size = _networkStream.Read(data, 0, data.Length);
received = Encoding.ASCII.GetString(data, 0, size);
return received;
}
private void btn_StopConnection_Click(object sender, EventArgs e)
{
_networkStream.Close();
_client.Close();
}
}
}
Here is I am adding the error and is coming from the ReadWrite method
enter image description here
So you'll have to have a loop somewhere to have your program keep checking the Stream. Usually the easiest was is with a Boolean indicator, so something list this:
Boolean openConnection = false;
This would need to be class level. Then inside your connect method, you loop and listen. Something like this.
NetworkStream ns = server.GetStream();
openConnection = True;
Task.Factory.StartNew(() =>
{
while (openConnection)
{
ns.Read(data, 0, data.Length);
var stringData = Encoding.ASCII.GetString(data, 0, 1024);
dataToAdd.Add(stringData);
foreach (var list in dataToAdd)
{
txt_BarcodeDisplay.Text += list + Environment.NewLine;
}
Thread.Sleep(2000);
}
}
);
So this is a lot to unpack, but basically you're saying, go read what comes in from the network, do it until the openConnection variable is set to false. Oh and since we don't want to peg the processor at 100%, Sleep the thread so we only check every 2 seconds.
This is a rough start, but I hope it will give you an idea of the direction you need to take this.

Visual Studio 2017 C# Sockets UDP

Im having a hard time figuring this out.
I'm trying to make a chat where there's one server and multiple clients but I can't seem to get it to work.
Im using Visual Studio 2017 and it's a Windows Forms App .NET Framework project. Now, it works but only 2 clients can connect to each other. If I try to connect two users to one, one gets blocked out of the conversation and can't recive messages from the server.
To the question: Is it possible to make a server that many clients can connect to and the server can send messages to all connected clients?
Code:
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;
using System.Net;
using System.Net.Sockets;
namespace ChatProgram
{
public partial class Window : Form
{
Socket sck;
EndPoint epLocal, epRemote;
public Window()
{
InitializeComponent();
sck = new Socket(AddressFamily.InterNetwork, SocketType.Dgram, ProtocolType.Udp); //Starts New Socket In InternNetwork Dgram Protocoltype UDP
sck.SetSocketOption(SocketOptionLevel.Socket, SocketOptionName.ReuseAddress, true);
IPMe.Text = GetLocalIP(); //Sets My IP Bar To My Local IP
}
private string GetLocalIP() //Gets Local IP From Computer
{
Send.Enabled = false;
IPHostEntry host;
host = Dns.GetHostEntry(Dns.GetHostName());
foreach (IPAddress ip in host.AddressList)
{
if (ip.AddressFamily == AddressFamily.InterNetwork)
{
return ip.ToString();
}
}
return "127.0.0.1";
}
private void MessageCallBack(IAsyncResult aResult)
{
try
{
int size = sck.EndReceiveFrom(aResult, ref epRemote);
if (size > 0)
{
byte[] recivedData = new byte[1464];
recivedData = (byte[])aResult.AsyncState;
ASCIIEncoding eEncoding = new ASCIIEncoding();
string recivedMessage = eEncoding.GetString(recivedData);
MessageBox.Items.Add("" + recivedMessage); //Paste Messages In MessageBox listMessage.Items.Add(""+recivedMessage);
}
byte[] buffer = new byte[1500];
sck.BeginReceiveFrom(buffer, 0, buffer.Length, SocketFlags.None, ref epRemote, new AsyncCallback(MessageCallBack), buffer);
}
catch (Exception exp)
{
System.Windows.Forms.MessageBox.Show(exp.ToString());
}
}
private void Connect_Click(object sender, EventArgs e)
{
try
{
epLocal = new IPEndPoint(IPAddress.Parse(IPMe.Text), Convert.ToInt32(PortMe.Text)); //MyPort And MyIP Make Port to Int32
sck.Bind(epLocal); //Socket Bind To epLocal
epRemote = new IPEndPoint(IPAddress.Parse(IpConnectingTo.Text), Convert.ToInt32(PortConnectingTo.Text)); //MyPort And MyIP Make Port to Int32
sck.Connect(epRemote); //Socket Bind To epRemote
byte[] buffer = new byte[1500];
sck.BeginReceiveFrom(buffer, 0, buffer.Length, SocketFlags.None, ref epRemote, new AsyncCallback(MessageCallBack), buffer);
Connect.Text = "Connected"; //Set Text To Connected
Connect.Enabled = false; //Disabled (Gray)
Send.Enabled = true; //Enable Send Button
TextBoxSendMessages.Focus(); //Set Focus To This!
}
catch (Exception ex)
{
System.Windows.Forms.MessageBox.Show(ex.ToString());
}
}
private void Send_Click(object sender, EventArgs e)
{
try
{
System.Text.ASCIIEncoding enc = new System.Text.ASCIIEncoding();
byte[] msg = new byte[1500];
string nickandtext = NickNameMe.Text + ": " + TextBoxSendMessages.Text;
msg = enc.GetBytes(nickandtext); //Messages The Sum Of Both
//msg = enc.GetBytes(NickNameMe.Text + TextBoxSendMessages.Text);
sck.Send(msg); //Send Message In Bytes
MessageBox.Items.Add(NickNameMe.Text + ": " + TextBoxSendMessages.Text); //See yourself msg in msgbox
TextBoxSendMessages.Clear(); //Clear Text Message Box
}
catch (Exception ex)
{
System.Windows.Forms.MessageBox.Show(ex.ToString());
}
}
private void IPMe_TextChanged(object sender, EventArgs e)
{
}
private void MessageBox_SelectedIndexChanged(object sender, EventArgs e)
{
}
private void label2_Click(object sender, EventArgs e)
{
}
}
}
Picture of program:

using System.Net.Sockets; not supported in windows store app architecture, what to use instead?

I created a simple client and server app in windows forms, now I wanted to create it in windows store app framework. using System.Net.Sockets; isnt supported there . How should I approach to this and what class should i use ? Following is the code in winforms c#: many thanks
using System.Net;
using System.Net.Sockets;
using System.Net.NetworkInformation;
using System.Media;
namespace ChatClient
{
public partial class Form1 : Form
{
Socket sck;
EndPoint epLocal, epRemote;
public Form1()
{
InitializeComponent();
//what would I use instead in windows store app, using System.Net.Sockets; namespace isnt supported ?
sck = new Socket(AddressFamily.InterNetwork, SocketType.Dgram, ProtocolType.Udp);
sck.SetSocketOption(SocketOptionLevel.Socket, SocketOptionName.ReuseAddress, true);
}
//Getting local IP address through code
private string GetLocalIP()
{
IPHostEntry host;
string localIP = "";
host = Dns.GetHostEntry(Dns.GetHostName());
foreach (IPAddress ip in host.AddressList)
{
if (ip.AddressFamily == AddressFamily.InterNetwork)
{
localIP = ip.ToString();
break;
}
}
return localIP;
}
private void MessageCallBack (IAsyncResult aResult)
{
try
{
int size = sck.EndReceiveFrom(aResult, ref epRemote);
if (size>0)
{
byte[] receivedData = new byte[1464];
receivedData = (byte[])aResult.AsyncState;
ASCIIEncoding eEncoding = new ASCIIEncoding();
string receiveMessage = eEncoding.GetString(receivedData);
listMessage.Items.Add("Friend : "+receiveMessage);
}
byte[] buffer = new byte[1500];
sck.BeginReceiveFrom(buffer, 0, buffer.Length, SocketFlags.None, ref epRemote, new AsyncCallback(MessageCallBack), buffer);
}
catch (Exception ex)
{
MessageBox.Show(ex.ToString());
}
}
private void textBox3_TextChanged(object sender, EventArgs e)
{
}
private void Form1_Load(object sender, EventArgs e)
{
groupBox1.Text = Environment.UserName;
textBox1.Text = GetLocalIP().ToString();
btnSend.Enabled = false;
}
private void btnStart_Click(object sender, EventArgs e)
{
try
{
if (CheckConnection() == 1)
{
btnStart.Text = "Please Wait...";
Thread.Sleep(2000);
epLocal = new IPEndPoint(IPAddress.Parse(textBox1.Text), Convert.ToInt32(comboBox1.Text));
sck.Bind(epLocal);
epRemote = new IPEndPoint(IPAddress.Parse(fndIP.Text), Convert.ToInt32(comboBox2.Text));
sck.Connect(epRemote);
byte[] buffer = new byte[1500];
sck.BeginReceiveFrom(buffer, 0, buffer.Length, SocketFlags.None, ref epRemote, new AsyncCallback(MessageCallBack), buffer);
btnStart.Enabled = false;
btnStart.Text = "Connected";
btnStart.BackColor = Color.LightGreen;
btnStart.ForeColor = Color.White;
btnSend.Enabled = true;
textBox5.Focus();
button1.Enabled = true;
}
else
{
MessageBox.Show("Check Your Internet connection");
}
}
catch(Exception ex1)
{
MessageBox.Show(ex1.ToString());
}
}
private void btnSend_Click(object sender, EventArgs e)
{
try
{
System.Text.ASCIIEncoding enc = new System.Text.ASCIIEncoding();
byte[] msg = new byte[1500];
msg = enc.GetBytes(textBox5.Text);
new SoundPlayer(Properties.Resources.chat).Play();
sck.Send(msg);
listMessage.Items.Add("Me : "+textBox5.Text);
new SoundPlayer(Properties.Resources.chat).Play();
textBox5.Clear();
}
catch(Exception ex)
{
MessageBox.Show(ex.ToString());
}
}
private void pictureBox1_Click(object sender, EventArgs e)
{
}
private int CheckConnection ()
{
Ping myPing = new Ping();
String host = "74.125.20.147";
byte[] buffer = new byte[32];
int timeout = 1000;
PingOptions pingOptions = new PingOptions();
PingReply reply = myPing.Send(host, timeout, buffer, pingOptions);
if (reply.Status == IPStatus.Success)
{
return 1;
}
else
{
return 0;
}
}
private void button1_Click(object sender, EventArgs e)
{
sck.Close();
}
}
}
From Windows 8 development > How to > How tos (XAML) > Connecting to networks and web services Connecting with sockets:
Send and receive data with TCP or UDP sockets in your Windows Runtime app using features in the Windows.Networking.Sockets namespace.
You use UDP, so see How to connect with a datagram socket (XAML) which uses the class Windows.Networking.Sockets.DatagramSocket.
It's in the Windows.Networking.Sockets namespace
See .Net for Windows Store Apps overview article for a complete description on how to deal with these differences.

Categories

Resources