Socket problem with Chat app
-
Hi, Im writing a very simple network chat app. This is only a chat app for two people over network. Here is my code:
public partial class MyChat : Form { Socket sock; Thread receiver; static IPAddress localIPAddr; static int intPort; IPEndPoint multiep; public MyChat() { InitializeComponent(); localIPAddr = IPAddress.Parse(txtHost.Text); intPort = Convert.ToInt32(txtPort.Text.ToString()); multiep = new IPEndPoint(localIPAddr, 4040); sock = new Socket(AddressFamily.InterNetwork, SocketType.Dgram, ProtocolType.Udp); IPEndPoint iep = new IPEndPoint(IPAddress.Any, intPort); sock.Bind(iep); **sock.SetSocketOption(SocketOptionLevel.IP, SocketOptionName.AddMembership, new MulticastOption(localIPAddr));** receiver = new Thread(new ThreadStart(packetReceive)); receiver.IsBackground = true; receiver.Start(); } void packetReceive() { EndPoint ep = (EndPoint)multiep; byte[] data = new byte[1024]; string stringData; int recv; while (true) { recv = sock.ReceiveFrom(data, ref ep); stringData = Encoding.ASCII.GetString(data, 0, recv); //results.Items.Add("from " + ep.ToString() + ": " + stringData); rtxtMsgWindow.AppendText("from " + ep.ToString() + ": " + stringData); } } private void btnExit_Click(object sender, EventArgs e) { receiver.Abort(); sock.Close(); Close(); } private void txtMessage_KeyPress(object sender, KeyPressEventArgs e) { if (e.Handled = e.KeyChar == 13) { byte[] message = Encoding.ASCII.GetBytes(txtMessage.Text); txtMessage.Clear(); sock.SendTo(message, SocketFlags.None, multiep); } } }
Problem is i get the following socket exception The requested address is not valid in its context at the line of code i made bold above. The specified ip address would be my own ip address to test and see if the message gets posted. If this is the problem is there any other way i could get around this maybe a different way of socket programming mayb