Error: The requested address is not valid in its context.
CodeGuru Home VC++ / MFC / C++ .NET / C# Visual Basic VB Forums Developer.com
Results 1 to 3 of 3

Thread: Error: The requested address is not valid in its context.

  1. #1
    Join Date
    Jun 2011
    Posts
    3

    Error: The requested address is not valid in its context.

    I am working on developing a client server application that currently provides simple chat functionality. The server application appears to be working properly listening on one port for a TCP connection and another for UDP messages. But, when the client attempts a connection I get an error thrown that says "The requested address is not valid in its context.". The server is currently running on one machine while the client is running on another. I am using a Unity 3d scene to run the client as eventually I would like to use this to develop a multiplayer game. Here is the source code for what I have. I have been working on this issue for days now and could really use the help. Thank you. This is .NET 3.5

    Server Main:

    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.Threading;
    using System.Collections;
    using System.Net.Sockets;

    namespace AxiomTestServer_Alpha_0_02
    {
    public partial class mainForm : Form
    {
    static void Main()
    {
    Application.Run(new mainForm());
    }

    public mainForm()
    {
    InitializeComponent();
    }

    const int PORT_NUM = 65000;
    private Hashtable clients = new Hashtable();
    private TcpListener listener;
    private Thread listenerThread;
    private UdpClient transmitter = new UdpClient(65002);
    private Thread transThread;


    private void ConnectUser(string userName, UserConnection sender)
    {
    if (clients.Contains(userName))
    {
    ReplyToSender("REFUSE", sender);
    }

    else
    {
    sender.Name = userName;
    UpdateStatus(sender.Name + " has joined the chat");
    clients.Add(userName, sender);
    ReplyToSender("JOIN", sender);
    SendToClients("CHAT|" + sender.Name + " has joined the chat.", sender);
    }
    }

    private void DisconnectUser(UserConnection sender)
    {
    UpdateStatus(sender.Name + " has left the chat.");
    SendToClients("CHAT|" + sender.Name + " has left the chat.", sender);
    clients.Remove(sender.Name);
    }

    private void ConnectionListen()
    {
    try
    {
    listener = new TcpListener(System.Net.IPAddress.Any, PORT_NUM);
    listener.Start();

    do
    {
    UserConnection client = new UserConnection(listener.AcceptTcpClient());
    client.LineRecieved += new LineRecieve(OnLineRecieved);
    UpdateStatus("Someone is attempting a login");

    } while (true);
    }
    catch
    {
    }
    }

    private void OnLineRecieved(UserConnection sender, string data)
    {
    string[] dataArray;

    dataArray = data.Split((char)124);

    switch (dataArray[0])
    {
    case "CONNECT":
    ConnectUser(dataArray[1], sender);
    break;
    case "CHAT":
    SendChat(dataArray[1], sender);
    break;
    case "DISCONNECT":
    DisconnectUser(sender);
    break;
    default:
    //let the users know this message was sent wrong
    break;
    }

    }

    private void receiveUDP()
    {
    while (true)
    {
    System.Net.IPEndPoint ipep = new System.Net.IPEndPoint(System.Net.IPAddress.Any, 65002);
    byte[] content = transmitter.Receive(ref ipep);

    if (content.Length > 0)
    {
    string message = Encoding.ASCII.GetString(content);
    string[] data = message.Split((char)124);

    UserConnection sender = (UserConnection)clients[data[0]];
    OnLineRecieved(sender, data[1]+ "|" + data[2]);
    }
    }
    }

    private void mainForm_Load(object sender, EventArgs e)
    {
    listenerThread = new Thread(ConnectionListen);
    listenerThread.IsBackground = true;
    listenerThread.Start();

    transThread = new Thread(receiveUDP);
    transThread.IsBackground = true;
    transThread.Start();
    UpdateStatus("Server Started");

    }

    private void SendToClients(string message, UserConnection sender)
    {
    UserConnection client;

    foreach (DictionaryEntry entry in clients)
    {
    client = (UserConnection)entry.Value;

    if (client.Name != sender.Name)
    {
    client.SendData(message);
    }
    }
    }

    private void SendChat(string message, UserConnection sender)
    {
    SendToClients("CHAT|" + sender.Name + ": " + message, sender);
    UpdateStatus(sender.Name + ": " + message);
    }

    private void ReplyToSender(string message, UserConnection sender)
    {
    sender.SendData(message);
    }

    private void Broadcast(string message)
    {
    UserConnection client;

    foreach (DictionaryEntry entry in clients)
    {
    client = (UserConnection)entry.Value;
    client.SendData(message);
    }
    }

    private void mainForm_FormClosing(object sender, FormClosingEventArgs e)
    {
    transThread.Abort();
    listenerThread.Abort();
    }

    public void UpdateStatus(string message)
    {
    textBox1.AppendText(message + "\n");
    }
    }
    }

    UserConnection:

    using System;
    using System.Collections.Generic;
    using System.Linq;
    using System.Text;
    using System.Net;
    using System.Net.Sockets;
    using System.IO;
    using System.Threading;

    namespace AxiomTestServer_Alpha_0_02
    {
    public delegate void LineRecieve(UserConnection sender, string data);

    public class UserConnection
    {
    const int READ_BUFFER_SIZE = 255;
    private TcpClient client;
    private byte[] readBuffer = new byte[READ_BUFFER_SIZE];
    private string strName;
    public IPEndPoint ipAdd;
    private UdpClient trans;


    public UserConnection(TcpClient client)
    {
    this.client = client;
    ipAdd = (IPEndPoint)client.Client.RemoteEndPoint;
    this.client.GetStream().BeginRead(readBuffer, 0, READ_BUFFER_SIZE, new AsyncCallback(StreamReciever), null);
    }

    public string Name
    {
    get
    {
    return strName;
    }

    set
    {
    strName = value;
    }
    }

    public event LineRecieve LineRecieved;

    public void SendData(string data)
    {
    trans = new UdpClient(65002);
    byte[] dataArr = Encoding.ASCII.GetBytes(data);
    trans.Send(dataArr, dataArr.Length, ipAdd);

    }

    public void StreamReciever(IAsyncResult ar)
    {
    int bytesRead;
    string strMessage;

    try
    {
    lock (client.GetStream())
    {
    bytesRead = client.GetStream().EndRead(ar);
    }

    strMessage = Encoding.ASCII.GetString(readBuffer, 0, bytesRead - 1);
    LineRecieved(this, strMessage);

    lock (client.GetStream())
    {
    client.GetStream().BeginRead(readBuffer, 0, READ_BUFFER_SIZE, new AsyncCallback(StreamReciever), null);
    }
    }
    catch (Exception e)
    {
    }
    }


    }
    }

    Client Connection Class:

    using System;
    using System.Collections.Generic;
    using System.Linq;
    using System.Text;
    using System.Net.Sockets;
    using System.Net;
    using System.Threading;
    using System.IO;

    namespace Axiom_ClientConnection_0_01
    {
    public class Connector
    {
    const int READ_BUFFER_SIZE = 255;
    const int TCP_PORT_NUMBER = 65000;
    const int UDP_PORT_NUMBER = 65002;
    private TcpClient connectionClient;
    private UdpClient transmissionClient = new UdpClient();// = new UdpClient(UDP_PORT_NUMBER);
    private byte[] readbuffer = new byte[READ_BUFFER_SIZE];
    public string message = "";
    public string result = "";
    private string username;
    IPEndPoint ipAddress;
    Thread UDPListenerThread;

    public Connector() { }

    public string ConnectionAttempt(string ServeIP, string PlayUsername)
    {
    username = PlayUsername;

    try
    {

    connectionClient = new TcpClient(ServeIP,TCP_PORT_NUMBER);
    connectionClient.GetStream().BeginRead(readbuffer, 0, READ_BUFFER_SIZE, new AsyncCallback(DoRead), null);

    Login(username);
    ipAddress = (IPEndPoint)connectionClient.Client.RemoteEndPoint;
    transmissionClient.Connect(ServeIP, UDP_PORT_NUMBER);
    UDPListenerThread = new Thread(receiveUDP);
    UDPListenerThread.IsBackground = true;
    UDPListenerThread.Start();
    return "Connection Succeeded";
    }
    catch(Exception ex) {
    return (ex.Message.ToString() + "Connection Failed");
    }
    }

    private void receiveUDP()
    {
    transmissionClient.Client.SetSocketOption(SocketOptionLevel.Socket, SocketOptionName.ReuseAddress, true);
    while (true)
    {
    System.Net.IPEndPoint ipep = new System.Net.IPEndPoint(System.Net.IPAddress.Any, UDP_PORT_NUMBER);
    byte[] content = transmissionClient.Receive(ref ipep);

    if (content.Length > 0)
    {
    string message = Encoding.ASCII.GetString(content);
    //string[] data = message.Split((char)124);

    ProcessCommands(message);
    }
    }
    }

    public void Login(string username)
    {
    StreamWriter writer = new StreamWriter(connectionClient.GetStream());
    writer.Write("CONNECT|" + username);
    writer.Flush();
    }

    public void PktTest(string data)
    {
    SendData(username + "|CHAT|" + data);
    }

    public void Disconnect()
    {
    SendData("DISCONNECT");
    UDPListenerThread.Abort();

    connectionClient.Close();
    transmissionClient.Close();
    }


    private void DoRead(IAsyncResult ar)
    {
    int BytesRead;
    try
    {
    BytesRead = connectionClient.GetStream().EndRead(ar);
    if (BytesRead < 1)
    {
    result = "DISCONNECTED";
    return;
    }

    string message = Encoding.ASCII.GetString(readbuffer, 0, BytesRead);
    ProcessCommands(message);

    connectionClient.GetStream().BeginRead(readbuffer, 0, READ_BUFFER_SIZE, new AsyncCallback(DoRead), null);
    }
    catch { }
    }


    private void SendData(string data)
    {
    byte[] dataArr = Encoding.ASCII.GetBytes(data);
    try
    {
    transmissionClient.Send(dataArr, dataArr.Length, ipAddress);
    }
    catch (Exception e)
    {
    }
    }

    private void ProcessCommands(string data)
    {
    string[] dataArr;

    dataArr = data.Split((char)124);

    switch (dataArr[0])
    {
    case "JOIN":
    result = "You have joined the chat!";
    break;
    case "CHAT":
    result = dataArr[1].ToString();
    break;
    case "REFUSE":
    Login(username);
    result = "Connection refused. Attempting another login.";
    break;
    case "BROAD":
    result = "SERVER MESSAGE: " + dataArr[1].ToString();
    break;
    default:
    result = "Server sent bad message waiting for retry";
    break;
    }
    }

    }
    }

    Unity Script for the Client connection:

    using UnityEngine;
    using System.Collections;
    using Axiom_ClientConnection_0_01;
    using System.Runtime.InteropServices;
    using System.Security.Permissions;

    public class LinkingClient : MonoBehaviour {

    public Connector testing = new Connector();
    string lastMessage = "";
    public Transform PlayerCoord;

    // Use this for initialization
    void Start () {
    Debug.Log(testing.ConnectionAttempt("192.168.11.7", System.Environment.MachineName).ToString());

    if (testing.result != "")
    {
    //Debug.Log(testing.result);
    }
    }

    // Update is called once per frame
    void Update () {
    if (Input.GetKeyDown("space"))
    {
    Debug.Log("space bar was pressed");
    testing.PktTest("space bar was pressed");
    }

    if (testing.message != "JOIN")
    {
    if (testing.result != lastMessage)
    {
    Debug.Log(testing.result);
    lastMessage = testing.result;
    }
    }

    testing.PktTest(PlayerCoord.position[0] + ", " + PlayerCoord.position[1] + ", " + PlayerCoord.position[2]);
    }

    void OnApplicationQuit()
    {
    try { testing.Disconnect(); }
    catch { }
    }


    }

  2. #2
    Join Date
    Jun 2008
    Posts
    2,477

    Re: Error: The requested address is not valid in its context.

    That is a ton of code. Can you break it down into something more simple and manageable that reproduces the issue?

  3. #3
    Join Date
    Feb 2011
    Location
    United States
    Posts
    1,005

    Re: Error: The requested address is not valid in its context.

    This thread appears to duplicate another one created on the same day: http://www.codeguru.com/forum/showthread.php?t=513529

    I suggest we discuss the issue there, if there is more to say.
    Best Regards,

    BioPhysEngr
    http://blog.biophysengr.net
    --
    All advice is offered in good faith only. You are ultimately responsible for effects of your programs and the integrity of the machines they run on.

Tags for this Thread

Posting Permissions

  • You may not post new threads
  • You may not post replies
  • You may not post attachments
  • You may not edit your posts
  •  


Azure Activities Information Page

Windows Mobile Development Center


Click Here to Expand Forum to Full Width

This is a CodeGuru survey question.


Featured


HTML5 Development Center