Wayback Machinekoobas.hobune.stream
May JUN Jul
Previous capture 12 Next capture
2021 2022 2023
1 capture
12 Jun 22 - 12 Jun 22
sparklines
Close Help
  • Products
  • Solutions
  • Made with Unity
  • Learning
  • Support & Services
  • Community
  • Asset Store
  • Get Unity

UNITY ACCOUNT

You need a Unity Account to shop in the Online and Asset Stores, participate in the Unity Community and manage your license portfolio. Login Create account
  • Blog
  • Forums
  • Answers
  • Evangelists
  • User Groups
  • Beta Program
  • Advisory Panel

Navigation

  • Home
  • Products
  • Solutions
  • Made with Unity
  • Learning
  • Support & Services
  • Community
    • Blog
    • Forums
    • Answers
    • Evangelists
    • User Groups
    • Beta Program
    • Advisory Panel

Unity account

You need a Unity Account to shop in the Online and Asset Stores, participate in the Unity Community and manage your license portfolio. Login Create account

Language

  • Chinese
  • Spanish
  • Japanese
  • Korean
  • Portuguese
  • Ask a question
  • Spaces
    • Default
    • Help Room
    • META
    • Moderators
    • Topics
    • Questions
    • Users
    • Badges
  • Home /
avatar image
0
Question by VenomousDevelopment · Jun 14, 2011 at 10:11 PM · serverclientsocketsudptcp

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.

Comment
Add comment · Show 4
10 |3000 characters needed characters left characters exceeded
â–¼
  • Viewable by all users
  • Viewable by moderators
  • Viewable by moderators and the original poster
  • Advanced visibility
Viewable by all users
avatar image VenomousDevelopment · Jun 15, 2011 at 10:28 PM 0
Share

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.

avatar image Meater6 · Jun 16, 2011 at 01:05 AM 0
Share

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.

avatar image VenomousDevelopment · Jun 16, 2011 at 03:12 AM 0
Share

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.

avatar image VenomousDevelopment · Jun 16, 2011 at 03:48 AM 0
Share

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

1 Reply

· Add your reply
  • Sort: 
avatar image
0

Answer by sandyakayika5730 · Sep 27, 2020 at 08:34 AM

@aldonaletto

Comment
Add comment · Share
10 |3000 characters needed characters left characters exceeded
â–¼
  • Viewable by all users
  • Viewable by moderators
  • Viewable by moderators and the original poster
  • Advanced visibility
Viewable by all users

Your answer

Hint: You can notify a user about this post by typing @username

Up to 2 attachments (including images) can be used with a maximum of 524.3 kB each and 1.0 MB total.

Follow this Question

Answers Answers and Comments

3 People are following this question.

avatar image avatar image avatar image

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


Enterprise
Social Q&A

Social
Subscribe on YouTube social-youtube Follow on LinkedIn social-linkedin Follow on Twitter social-twitter Follow on Facebook social-facebook Follow on Instagram social-instagram

Footer

  • Purchase
    • Products
    • Subscription
    • Asset Store
    • Unity Gear
    • Resellers
  • Education
    • Students
    • Educators
    • Certification
    • Learn
    • Center of Excellence
  • Download
    • Unity
    • Beta Program
  • Unity Labs
    • Labs
    • Publications
  • Resources
    • Learn platform
    • Community
    • Documentation
    • Unity QA
    • FAQ
    • Services Status
    • Connect
  • About Unity
    • About Us
    • Blog
    • Events
    • Careers
    • Contact
    • Press
    • Partners
    • Affiliates
    • Security
Copyright © 2020 Unity Technologies
  • Legal
  • Privacy Policy
  • Cookies
  • Do Not Sell My Personal Information
  • Cookies Settings
"Unity", Unity logos, and other Unity trademarks are trademarks or registered trademarks of Unity Technologies or its affiliates in the U.S. and elsewhere (more info here). Other names or brands are trademarks of their respective owners.
  • Anonymous
  • Sign in
  • Create
  • Ask a question
  • Spaces
  • Default
  • Help Room
  • META
  • Moderators
  • Explore
  • Topics
  • Questions
  • Users
  • Badges