Visual Studio 2017 C# Sockets UDP - c#

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:

Related

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();
}
}
}

UDP Client C# - No Such Host is Known

I am battling to connect to a website using udpclient. Whenever I connect to localhost, I have no problems. This is the code I am using :'
private void button1_Click(object sender, EventArgs e)
{
UdpClient udpClient = new UdpClient();
udpClient.Connect("www.ituran.com/ituranmobileservice/mobileservice.asmx", 45004);
Byte[] btSendData = Encoding.ASCII.GetBytes("TESTING");
udpClient.Send(btSendData, btSendData.Length);
}
public void serverThread()
{
try
{
UdpClient udpClient = new UdpClient(45004);
while (true)
{
IPEndPoint RemoteIpEndPoint = new IPEndPoint(IPAddress.Any, 0);
Byte[] btRecieve = udpClient.Receive(ref RemoteIpEndPoint);
string strReturnData = Encoding.ASCII.GetString(btRecieve);
Console.WriteLine(RemoteIpEndPoint.Address.ToString() + ":" + strReturnData.ToString());
}
}
catch (Exception ex)
{
using (StreamWriter sw = new StreamWriter("TEST_errorLog.txt", true))
{
sw.WriteLine();
sw.WriteLine(ex.ToString());
}
}
}
private void Form1_Load(object sender, EventArgs e)
{
Thread thdUDPServer = new Thread(new ThreadStart(serverThread));
thdUDPServer.IsBackground = true;
thdUDPServer.Start();
}
The people that sent me the URL has confimed five times that the address and port is correct. How can I connect to that address?
Any help would be appreciated.
Change the host name to just www.ituran.com. There are no paths in UDP - you are just sending packets to a port on a server.

windows form app sending strings

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 :)

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.

Creating C# TCP server

I am trying to make a Server app and client app to connect through internet using C#.
Here is my Server app...
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 Server
{
public partial class Form1 : Form
{
private byte[] data = new byte[1024];
private int size = 1024;
private Socket server;
public Form1()
{
InitializeComponent();
}
private void Form1_Load(object sender, EventArgs e)
{
this.ControlBox = false;
}
private void button1_Click(object sender, EventArgs e)
{
this.Close();
}
private void button2_Click(object sender, EventArgs e)
{
server = new Socket(AddressFamily.InterNetwork,
SocketType.Stream, ProtocolType.Tcp);
IPEndPoint iep = new IPEndPoint(System.Net.IPAddress.Any, 8001);
server.Bind(iep);
server.Listen(1);
server.BeginAccept(new AsyncCallback(AcceptConn), server);
textBox1.Text = "Server Started!! \r\nWaiting for client...";
}
void AcceptConn(IAsyncResult iar)
{
Socket oldserver = (Socket)iar.AsyncState;
Socket client = oldserver.EndAccept(iar);
textBox1.Text = "Connected to: " + client.RemoteEndPoint.ToString();
string stringData = "Welcome to my server";
byte[] message1 = Encoding.ASCII.GetBytes(stringData);
client.BeginSend(message1, 0, message1.Length, SocketFlags.None,
new AsyncCallback(SendData), client);
}
void SendData(IAsyncResult iar)
{
Socket client = (Socket)iar.AsyncState;
int sent = client.EndSend(iar);
client.BeginReceive(data, 0, size, SocketFlags.None,
new AsyncCallback(ReceiveData), client);
}
void ReceiveData(IAsyncResult iar)
{
Socket client = (Socket)iar.AsyncState;
int recv = client.EndReceive(iar);
if (recv == 0)
{
client.Close();
textBox1.Text = "Waiting for client...";
server.BeginAccept(new AsyncCallback(AcceptConn), server);
return;
}
string receivedData = Encoding.ASCII.GetString(data, 0, recv);
listBox1.Items.Add(receivedData);
byte[] message2 = Encoding.ASCII.GetBytes(receivedData);
client.BeginSend(message2, 0, message2.Length, SocketFlags.None,
new AsyncCallback(SendData), client);
}
private void label1_Click(object sender, EventArgs e)
{
}
private void button3_Click(object sender, EventArgs e)
{
server.Close();
//server.Shutdown();
}
void ButtonStopOnClick(object obj, EventArgs ea)
{
Close();
}
}
}
And here is my Client app...
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
{
private TextBox newText;
private TextBox conStatus;
private ListBox results;
private Socket client;
private byte[] data = new byte[1024];
private int size = 1024;
public Form1()
{
InitializeComponent();
}
private void Form1_Load(object sender, EventArgs e)
{
this.ControlBox = false;
}
private void button1_Click(object sender, EventArgs e)
{
this.Close();
}
private void button2_Click(object sender, EventArgs e)
{
textBox2.Text = "Connecting...";
Socket newsock = new Socket(AddressFamily.InterNetwork,
SocketType.Stream, ProtocolType.Tcp);
IPEndPoint iep = new IPEndPoint(IPAddress.Parse("192.168.0.3"), 8001);
//IPEndPoint iep = new IPEndPoint(IPAddress.Parse("41.232.217.55"), 8001);
newsock.BeginConnect(iep, new AsyncCallback(Connected), newsock);
}
private void button3_Click(object sender, EventArgs e)
{
byte[] message = Encoding.ASCII.GetBytes(textBox1.Text);
textBox1.Clear();
client.BeginSend(message, 0, message.Length, SocketFlags.None,
new AsyncCallback(SendData), client);
}
private void button4_Click(object sender, EventArgs e)
{
client.Close();
textBox2.Text = "Disconnected";
}
void Connected(IAsyncResult iar)
{
client = (Socket)iar.AsyncState;
try
{
client.EndConnect(iar);
textBox2.Text = "Connected to: " + client.RemoteEndPoint.ToString();
client.BeginReceive(data, 0, size, SocketFlags.None,
new AsyncCallback(ReceiveData), client);
}
catch (SocketException)
{
textBox2.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);
listBox1.Items.Add(stringData);
}
void SendData(IAsyncResult iar)
{
Socket remote = (Socket)iar.AsyncState;
int sent = remote.EndSend(iar);
remote.BeginReceive(data, 0, size, SocketFlags.None,
new AsyncCallback(ReceiveData), remote);
}
}
}
I understand that the server app can use IPaddress.Any but the client must be specific to reach the server.
My problem is that i cant connect form another computer outside the local addressing (192.168.0.1, 192.168.0.2,....). I want the client to be able to connect to my server using my remote IP (41.232.217.55).

Categories

Resources