- Home /
Error: The requested address is not valid in its context.
Help would be much appreciated on my topic. I have been working on a client server application that will server as the basis for a multiplayer game that myself and a few other people are developing. I am starting off small attempting to just have the server and client be able to chat then expand functionality from there. I have run into an issue with connecting with both TCP and UDP as I am using both protocols in this application. TCP establishes the connection and UDP sends all of the basic messages and data. The error that I am getting occurs when the server and client are on two different machines in my local network. I can't run them on the same machine because they are not configured to share ports. The error I am getting is: The requested address is not valid in its context. I have tried researching this error on msdn and other forums. I have tried changing the ports that were being used and attempted to configure the connections to share ports. I also checked IP addresses multiple times. Attempted connections on different machines and set up port forwarding on my router so that it would access the server from the internet. All with no luck. My code is as follows. I appreciate any help at all that you can give me. I am really stumped by this one. It is all using C#.
Server Main Form 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.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 Class:
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 DLL 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(); 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 Client Connection Script
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 () {
//line below is what is highlighted by the error.
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 { }
}
}
Thank you for the help in advance.
I could really use some help with this. It is necessary to move my proposal within my organization forward. Any help at all with Unity networking would be great.
Try to format your script better, for I can't tell if there is 1 very long script or 3 long scripts. It would help us here answer your question if had better formatting.
Ok Ill give it a try. The code is actually 4 files. The first two are a separate server application that unity interfaces with. The third script is a dll to provide networking functionality to unity. The final is the script that is marked in the error the error. It occurs in the line Debug.Log(testing.ConnectionAttempt("192.168.11.7", System.Environment.$$anonymous$$achineName).ToString());
Thank you for taking a look and I will edit the original post so that it is easier to read.
I have finally figured out part of my problem. Unity is having problems running both TCP and UDP at the same time. I will have to do a little more searching as to why this is. If anyone has any suggestions please let me know
Your answer
Follow this Question
Related Questions
Multicast group or a list with all players ? 0 Answers
How to do a TCP Server? 4 Answers
How i could display or use data from another program 0 Answers
What's the best approach for creating a secure authorative server? 0 Answers
Receiving UDP data in Unity? 0 Answers