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 aeequs · Apr 28, 2017 at 05:52 AM · unity 5networkingserverclient

Connect to Server on different computer (local network)

Hola,

I'm currently trying to set up a basic client-to-server network for Unity. At the moment, the server is a separate Unity project on a different computer in the same network. I'm extremely new to uNet and the way Unity handles it's networking, so help is appreciated!

Essentially, the problem is that I'm trying to connect my client-side test project to a server project, on a different computer, on the same local network.

For whatever reason, the connection isn't coming through nor is it updating my servers connections in any way, despite having the right public IP address for the servers computer (didn't specify in code examples - it's specified in the Inspector).

Here is the client-side code:

using UnityEngine; using System.Collections.Generic; using UnityEngine.UI; using UnityEngine.Networking; using System.IO; using System.Runtime.Serialization.Formatters.Binary;

 public class ClientConnector : NetworkManager
 {
     NetworkClient m_client;
 
     public GameObject screenCanvas;
     bool socketConnection = false;
     bool serverConnection = false;
     bool connectingToSocket = false;
     bool connectingToServer = false;
     bool connectedToServer = false;
 
     public int socketConnectionPort = 8888;
     public int serverConnectionPort = 8899;
     public string connectionIP = "127.0.0.1";
     public int maxConnectionsNumber = 10;
 
     int reliableChannelID;
     int socketID;
     int socketConnectionID;
     int serverConnectionID;
 
     void Start ()
     {
         NetworkTransport.Init();
         m_client = new NetworkClient();
 
         if (SetupConnection())
         {
             ConnectSocket();
         }
 
         if (socketConnection)
         {
             ConnectServer();
         }
     }
     
     void OnApplicationQuit()
     {
         NetworkTransport.Shutdown();
     }
 
     public void ConnectSocket()
     {
         connectingToSocket = true;
         byte error;
         socketConnectionID = NetworkTransport.Connect(socketID, connectionIP, socketConnectionPort, 0, out error);
 
         if (socketConnectionID != 0)
         {
             socketConnection = true;
             connectingToSocket = false;
         }
     }
 
     public void ConnectServer()
     {
         connectingToServer = true;
         byte error;
         serverConnectionID = NetworkTransport.Connect(socketID, connectionIP, serverConnectionPort, 0, out error);
 
         if (serverConnectionID != 0)
         {
             serverConnection = true;
             connectedToServer = true;
             connectingToServer = false;
 
             SendSocketMessage();
         }
     }
 
     bool SetupConnection()
     {
         ConnectionConfig config = new ConnectionConfig();
 
         reliableChannelID = config.AddChannel(QosType.Reliable);
 
         HostTopology topology = new HostTopology(config, maxConnectionsNumber);
         socketID = NetworkTransport.AddHost(topology, socketConnectionPort);
         if (client != null)
         {
             client.RegisterHandler(MsgType.Connect, OnConnected);
         }
 
         if (socketID == 0)
         {
             Debug.Log("Socket open. Socket ID is: " + socketConnectionID);
             return true;
         }
         else
         {
             return false;
         }
 
     }
 
     void Update ()
     {
         ReceiveAndHandlePacket();
     }
 
     void ReceiveAndHandlePacket()
     {
         int recChannelID;
         byte[] recBuffer = new byte[1024];
         int bufferSize = 1024;
         int dataSize;
         byte error;
 
         NetworkEventType networkEvent = NetworkTransport.Receive(out socketID, out socketConnectionID, out recChannelID, recBuffer, bufferSize, out dataSize, out error);
 
         switch (networkEvent)
         {
             case NetworkEventType.Nothing:
                 {
                     Debug.Log("No packets!");
                     break;
                 }
 
             case NetworkEventType.ConnectEvent:
                 {
                     break;
                 }
 
             case NetworkEventType.DataEvent:
                 {
                     Stream stream = new MemoryStream(recBuffer);
                     bufferSize = (int)stream.Position;
                     BinaryFormatter formatter = new BinaryFormatter();
                     string data = formatter.Deserialize(stream) as string;
                     Debug.Log("Received Packet from Server saying: " + data);
                     break;
                 }
 
             case NetworkEventType.DisconnectEvent:
                 {
                     Debug.Log("Disconnected.");
                     break;
                 }                
         }
     }
     
     void SendSocketMessage()
     {
         byte error;
         byte[] buffer = new byte[1024];
         Stream stream = new MemoryStream(buffer);
         BinaryFormatter formatter = new BinaryFormatter();
         formatter.Serialize(stream, "Connecting from Client.");
 
         int bufferSize = (int)stream.Position;
 
         NetworkTransport.Send(socketID, socketConnectionID, reliableChannelID, buffer, bufferSize, out error);
     }    
 
     void OnConnected(NetworkMessage netMsg)
     {
         Debug.Log("Connected to Socket on " + connectionIP);
     }
 }

and here is the server-side code:

 using UnityEngine;
 using System.Collections.Generic;
 using UnityEngine.UI;
 using UnityEngine.Networking;
 using System.IO;
 using System.Runtime.Serialization.Formatters.Binary;    
 public class ServerControl : NetworkManager
 {
     public GameObject connectionsScreen;
     public int maxConnectables;
     public int socketConnectionPort = 8888;
     public string socketConnectionIP = "127.0.0.1";
     public int serverConnectionPort = 8899;
 
     bool useNat;
     List<NetworkClient> connections = new List<NetworkClient>();
 
     bool serverInitialized;
     int channelID;
     int socketID;
     int connectionID;
 
     void Start()
     {
         useNat = !Network.HavePublicAddress();
         NetworkTransport.Init();
 
         if (SetupSocket())
         {
             InitializePeerServer();
         }                
     }
     
     void OnApplicationQuit()
     {
         NetworkTransport.Shutdown();
     }
 
     public bool SetupSocket()
     {
         ConnectionConfig config = new ConnectionConfig();
         channelID = config.AddChannel(QosType.Reliable);
 
         HostTopology topology = new HostTopology(config, maxConnections);
         socketID = NetworkTransport.AddHost(topology);
 
         byte error;
         connectionID = NetworkTransport.Connect(socketID, socketConnectionIP, socketConnectionPort, 0, out error);
 
         if (connectionID != 0)
         {
             Debug.Log("Socket open on: " + socketConnectionPort + " with IP: " + socketConnectionIP);
             return true;
         }
         else
             return false;
     }
 
     public void InitializePeerServer()
     {
         NetworkConnectionError serverStatus;
         serverStatus = Network.InitializeServer(maxConnectables, serverConnectionPort, useNat);
 
         switch (serverStatus)
         {
             case NetworkConnectionError.NoError:
                 {
                     serverInitialized = true;
                     break;
                 }
 
             default:
                 {
                     serverInitialized = false;
                     break;
                 }
         }
     }
 
     public void ReceiveAndHandlePackets()
     {
         int recChannelID;
         byte[] recBuffer = new byte[1024];
         int bufferSize = 1024;
         int dataSize;
         byte error;
         NetworkEventType networkEvent = NetworkTransport.Receive(out socketID, out connectionID, out recChannelID, recBuffer, bufferSize, out dataSize, out error);
 
         switch (networkEvent)
         {
             case NetworkEventType.Nothing:
                 connectionsScreen.transform.GetChild(6).GetComponent<Text>().text = "Message: \nNo packets!";
                 break;
 
             case NetworkEventType.ConnectEvent:
                 {
                     Debug.Log("Incoming connection.");
                     break;
                 }
 
             case NetworkEventType.DataEvent:
                 {
                     Stream stream = new MemoryStream(recBuffer);
                     BinaryFormatter formatter = new BinaryFormatter();
                     string data = formatter.Deserialize(stream) as string;
                     Debug.Log("Received packet, saying: " + data);
                     connectionsScreen.transform.GetChild(6).GetComponent<Text>().text = "Message Received: " + data;
                     break;
                 }
 
             case NetworkEventType.DisconnectEvent:
                 {
                     Debug.Log("Disconnected.");
                     break;
                 }
         }
     }
 
     public override void OnClientConnect(NetworkConnection conn)
     {
         base.OnClientConnect(conn);
 
         NetworkClient client = new NetworkClient(conn);
         connections.Add(client);
         Debug.Log("New connection from " + conn.address);
     }
 }

Any & all help is greatly appreciated! Thanks a bunch.

Comment
Add comment
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

0 Replies

· Add your reply
  • Sort: 

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

Server not receiving message? 1 Answer

Unity networking tutorial? 6 Answers

Creating a multiplayer game. 1 Answer

Can a person be both a client and a server? (and more) 0 Answers

How can a client connect more players to a network game? 1 Answer


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