Hi I want create a server connection between two computers with C#.
Here is the source code I've tried:
Socket sks;
EndPoint epLocal, epRemote;
byte[] buffer;
private void Form2_Load(object sender, EventArgs e)
{
sks = new Socket(AddressFamily.InterNetwork, SocketType.Dgram, ProtocolType.Udp);
sks.SetSocketOption(SocketOptionLevel.Socket, SocketOptionName.ReuseAddress, true);
textLocalIp.Text = GetLocalIP();
textFriendsIp.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 button2_Click(object sender, EventArgs e)
{
try
{ // binding socket
epLocal = new IPEndPoint(IPAddress.Parse(textLocalIp.Text), Convert.ToInt32(textLocalPort.Text));
sks.Bind(epLocal);
// connect to remote IP and port
epRemote = new IPEndPoint(IPAddress.Parse(textFriendsIp.Text), Convert.ToInt32(textFriendsPort.Text));
sks.Connect(epRemote);
buffer = new byte[1500];
sks.BeginReceiveFrom(buffer, 0, buffer.Length, SocketFlags.None, ref epRemote, new
AsyncCallback(MessageCallBack), buffer);
// release button to send message
button2.Text = "Connected";
}
catch (Exception ex)
{
MessageBox.Show(ex.ToString());
}
}
private void button1_Click(object sender, EventArgs e)
{
textBox5.Text = "Rock";
try
{ // converts from string to byte[]
System.Text.ASCIIEncoding enc = new System.Text.ASCIIEncoding();
byte[] msg = new byte[1500];
msg = enc.GetBytes(textBox5.Text);
// sending the message
sks.Send(msg);
// add to listbox
listBox1.Items.Add("You:+ " + textBox5.Text);
// clear txtMessage
textBox5.Clear();
}
catch (Exception ex)
{
MessageBox.Show(ex.ToString());
}
}
private void MessageCallBack(IAsyncResult aResult)
{
try
{
int size = sks.EndReceiveFrom(aResult, ref epRemote);
// check if theres actually information if (size > 0) { // used to help us on getting the data
byte[] receivedData = new byte[1464];
// getting the message data
receivedData = (byte[])aResult.AsyncState;
// converts message data byte array to string
ASCIIEncoding eEncoding = new ASCIIEncoding();
string receivedMessage = eEncoding.GetString(receivedData);
// adding Message to the listbox
listBox1.Items.Add("Friend: " + receivedMessage);
}
catch (Exception exp)
{
MessageBox.Show(exp.ToString());
}
// starts to listen the socket again
buffer = new byte[1500];
sks.BeginReceiveFrom(buffer, 0, buffer.Length, SocketFlags.None, ref epRemote, new AsyncCallback(MessageCallBack), buffer);
}
}
But when I try this out entering my IP and port and the other device's IP and port, it throws this exception::