puneet ahooja

puneet ahooja

  • NA
  • 97
  • 20.7k

I am creating the ip chat program but its getting error ?

Jan 4 2016 5:30 AM
Dear Friends,
 
I am creating/ Learning  the Ip Chat Program  in c#, but its getting error.
 
Send you the screen shots for your reference.
my whole network is in DHCP integrated.
 
Can any one helps for getting/ resolve  this error.
 
Here is the Code:
 
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;
using System.Net;
using System.Net.Sockets;
namespace ChatApp
{
public partial class Form1 : Form
{
Socket sck;
EndPoint epLocal, epRemote;
byte[] buffer;
public Form1()
{
InitializeComponent();
}
private void Form1_Load(object sender, EventArgs e)
{
// set up socket
sck = new Socket(AddressFamily.InterNetwork, SocketType.Dgram, ProtocolType.Udp);
sck.SetSocketOption(SocketOptionLevel.Socket, SocketOptionName.ReuseAddress, true);
//get user IP
textLocalIp.Text = GetLocalIP();
textRemoteIp.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 buttonConnect_Click(object sender, EventArgs e)
{
// Binding Socket
epLocal = new IPEndPoint(IPAddress.Parse(textLocalIp.Text), Convert.ToInt32(textLocalIp.Text));
sck.Bind(epLocal);
// Connecting to Remote Ip
epRemote = new IPEndPoint(IPAddress.Parse(textRemoteIp.Text), Convert.ToInt32(textRemotePort.Text));
sck.Connect(epRemote);
// Listning the specific port
buffer = new byte[1500];
sck.BeginReceiveFrom(buffer, 0, buffer.Length, SocketFlags.None, ref epRemote, new AsyncCallback(MessageCallBack), buffer);
}
private void MessageCallBack(IAsyncResult aResult)
{
try
{
byte[] receivedData = new byte[1500];
receivedData = (byte[])aResult.AsyncState;
// Converting bytes to string
ASCIIEncoding aEncoding = new ASCIIEncoding();
string receivedMessage = aEncoding.GetString(receivedData);
//Adding this lessage into list box
listMessage.Items.Add("Friend:" + receivedMessage);
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 buttonSend_Click(object sender, EventArgs e)
{
//convert string message to byte[]
ASCIIEncoding aEncoding = new ASCIIEncoding();
byte[] sendingMessage = new byte[1500];
sendingMessage = aEncoding.GetBytes(textMessge.Text);
//sending the encoded messsage
sck.Send(sendingMessage);
//Adding to the list box
listMessage.Items.Add("Me:" + textMessge.Text);
textMessge.Text = "";
}
}
}
 
 
 
 
 
 
 

Answers (1)