Search Unity

Sockets Errors

Discussion in 'Scripting' started by Deleted User, Mar 21, 2019.

  1. Deleted User

    Deleted User

    Guest

    Hi, i am tryng to make a TCP/IP server/client using Unity engine and Visual Studio Console Application.

    Errors: When i try enter in game the Server Console show the message i Connected, but int the Game aplication(Unity) dont show nothing.
    And When i try send login data in game to server always give a error null references in NetworkStream.

    P.S: Iam new using Sockets, the Mysql dataBase works fine, the erros is in sockets data.

    The Game Application(Unity)Code
    Network.cs
    Code (CSharp):
    1. using System.Collections;
    2. using System.Collections.Generic;
    3. using UnityEngine;
    4. using System.Net.Sockets;
    5. using System.IO;
    6. using System;
    7.  
    8. public class Network : MonoBehaviour
    9. {
    10.     public static Network singleton;
    11.  
    12.     [Header("Network Settings")]
    13.     public string ServerIP = "127.0.0.1";
    14.     public int ServerPort = 5500;
    15.     public bool isConnected;
    16.  
    17.     public TcpClient PlayerSocket;
    18.     private NetworkStream myStream;
    19.  
    20.     private byte[] asyncBuff;
    21.     public bool shouldHandleData;
    22.     private byte[] myBytes = new byte[1024];
    23.  
    24.     private void Awake()
    25.     {
    26.         singleton = this;
    27.     }
    28.  
    29.     void Start()
    30.     {
    31.         ConnectGameServer();
    32.     }
    33.  
    34.     void ConnectGameServer()
    35.     {
    36.        
    37.         PlayerSocket = new TcpClient(ServerIP,ServerPort);
    38.         PlayerSocket.ReceiveBufferSize = 1024;
    39.         PlayerSocket.SendBufferSize = 1024;
    40.         PlayerSocket.NoDelay = false;
    41.         Array.Resize(ref asyncBuff, 2048);
    42.         PlayerSocket.BeginConnect(ServerIP, ServerPort, new AsyncCallback(ConnectCallback), PlayerSocket);
    43.         isConnected = true;
    44.     }
    45.  
    46.     void ConnectCallback(IAsyncResult result)
    47.     {
    48.         if (PlayerSocket != null)
    49.         {
    50.  
    51.             PlayerSocket.EndConnect(result);
    52.  
    53.             if (PlayerSocket.Connected == false)
    54.             {
    55.                 isConnected = false;
    56.                 return;
    57.             }
    58.             else
    59.             {
    60.  
    61.                 PlayerSocket.NoDelay = true;
    62.                 myStream = PlayerSocket.GetStream();
    63.                 myStream.BeginRead(asyncBuff, 0, 2048, OnReceive, null);
    64.             }
    65.         }
    66.     }
    67.  
    68.     private void Update()
    69.     {
    70.         if (shouldHandleData)
    71.         {
    72.             ClientHandleData.singleton.HandleData(myBytes);
    73.             shouldHandleData = false;
    74.         }
    75.     }
    76.  
    77.     void OnReceive(IAsyncResult result)
    78.     {
    79.         if (PlayerSocket != null)
    80.         {
    81.             if (PlayerSocket == null) return;
    82.  
    83.             int byteArray = myStream.EndRead(result);
    84.              myBytes = null;
    85.             Array.Resize(ref myBytes, byteArray);
    86.             Buffer.BlockCopy(asyncBuff, 0, myBytes, 0, byteArray);
    87.  
    88.             if (byteArray == 0)
    89.             {
    90.                 Debug.Log("You got disconnected from the Server.");
    91.                 PlayerSocket.Close();
    92.                 return;
    93.             }
    94.  
    95.             shouldHandleData = true;
    96.  
    97.             if (PlayerSocket == null)
    98.                 return;
    99.             myStream.BeginRead(asyncBuff, 0, 2048, OnReceive, null);
    100.         }
    101.     }
    102.  
    103.     public void WriteBytes(byte[] data, int startOfsset, int size)
    104.     {
    105.         try
    106.         {
    107.             myStream.Write(data, startOfsset, size);
    108.         }
    109.         catch (Exception e)
    110.         {
    111.             print("Error: " + e.ToString()); // for some rason always execute the exception
    112.         }
    113.        
    114.     }
    115.  
    116. }
    117.  
    ClientHandleData.cs
    Code (CSharp):
    1. using System;
    2. using UnityEngine;
    3. using UnityEngine.UI;
    4. using ByteBufferDLL;
    5.  
    6. class ClientHandleData : MonoBehaviour
    7. {
    8.     public static ClientHandleData singleton;
    9.  
    10.     private void Awake()
    11.     {
    12.         singleton = this;
    13.     }
    14.  
    15.     void HandleMessages(int packetNum, byte[] data)
    16.     {
    17.         switch (packetNum)
    18.         {
    19.             case 10:
    20.                 HandleLoginSucess(packetNum,data);
    21.                 break;
    22.             case 11:
    23.                 HandleLoginFailed(packetNum, data);
    24.                 break;
    25.             case 12:
    26.              
    27.                 break;
    28.             case 13:
    29.              
    30.                 break;
    31.             case 14:
    32.  
    33.                 break;
    34.             case 15:
    35.                 HandleWelcomeMessage(packetNum, data);
    36.                 break;
    37.             default:
    38.                 HandleUnknowPackage(packetNum, data);
    39.                 break;
    40.  
    41.         }
    42.     }
    43.  
    44.  
    45.  
    46.     public void HandleData(byte[] data)
    47.     {
    48.         int packetnum;
    49.         ByteBuffer buffer = new ByteBuffer();
    50.         buffer.WriteBytes(data);
    51.         packetnum = buffer.ReadInt();
    52.         buffer = null;
    53.         if (packetnum == 0)
    54.             return;
    55.  
    56.         HandleMessages(packetnum, data);
    57.     }
    58.  
    59.     void HandleLoginSucess(int packageNum, byte[] data)
    60.     {
    61.         ByteBuffer buffer = new ByteBuffer();
    62.         buffer.WriteBytes(data);
    63.         buffer.ReadInt();
    64.         var msg = buffer.ReadString();
    65.         InGameDebug.singleton.Debug("Login Message: " + msg,10f);
    66.         buffer = null;
    67.     }
    68.  
    69.     void HandleLoginFailed(int packageNum, byte[] data)
    70.     {
    71.         ByteBuffer buffer = new ByteBuffer();
    72.         buffer.WriteBytes(data);
    73.         buffer.ReadInt();
    74.         var msg = buffer.ReadString();
    75.         InGameDebug.singleton.Debug( msg, 10f);
    76.         buffer = null;
    77.     }
    78.  
    79.     private void HandleWelcomeMessage(int packetNum, byte[] data)
    80.     {
    81.         ByteBuffer buffer = new ByteBuffer();
    82.         buffer.WriteBytes(data);
    83.         buffer.ReadInt();
    84.         var msg = buffer.ReadString();
    85.         InGameDebug.singleton.Debug(msg, 10f);
    86.         buffer = null;
    87.     }
    88.  
    89.     private void HandleUnknowPackage(int packetNum, byte[] data)
    90.     {
    91.         ByteBuffer buffer = new ByteBuffer();
    92.         buffer.WriteBytes(data);
    93.         buffer.ReadInt();
    94.         var msg = buffer.ReadString();
    95.         InGameDebug.singleton.Debug("Unknow Message: "+msg, 10f);
    96.         buffer = null;
    97.     }
    98.  
    99.  
    100. }
    101.  
    ServerSendData.cs
    Code (CSharp):
    1. using System.Collections;
    2. using System.Collections.Generic;
    3. using UnityEngine;
    4. using UnityEngine.UI;
    5. using ByteBufferDLL;
    6.  
    7. public class ClientSendData : MonoBehaviour
    8. {
    9.  
    10.     public static ClientSendData sinleton;
    11.      Network network;
    12.  
    13.     // Use this for initialization
    14.     void Awake()
    15.     {
    16.         sinleton = this;
    17.         network = FindObjectOfType<Network>();
    18.     }
    19.  
    20.  
    21.     public void SendDataToServer(byte[] data)
    22.     {
    23.         ByteBuffer buffer = new ByteBuffer();
    24.         buffer.WriteBytes(data);
    25.         Network.singleton.WriteBytes(buffer.ToArray(), 0, buffer.ToArray().Length);
    26.         buffer = null;
    27.     }
    28.  
    29.     public void SendLogin(string username, string password)
    30.     {
    31.         ByteBuffer buff = new ByteBuffer();
    32.         buff.WriteInt(1);
    33.         buff.WriteString(username);
    34.         buff.WriteString(password);
    35.         SendDataToServer(buff.ToArray());
    36.         buff = null;
    37.     }
    38.  
    39.     public void SendRegister(string username, string password, string email)
    40.     {
    41.         ByteBuffer buff = new ByteBuffer();
    42.         buff.WriteInt(2);
    43.         buff.WriteString(username);
    44.         buff.WriteString(password);
    45.         buff.WriteString(email);
    46.         SendDataToServer(buff.ToArray());
    47.         buff = null;
    48.     }
    49. }
    50.  


    The Server Console Application Codes
    ServerHandleData.cs

    Code (CSharp):
    1. using System;
    2.  
    3. using System.Collections.Generic;
    4. using System.Linq;
    5. using System.Text;
    6. using ByteBufferDLL;
    7.  
    8. namespace CalixServer2
    9. {
    10.     class ServerHandleData
    11.     {
    12.         public static ServerHandleData singleton = new ServerHandleData();
    13.         private delegate void Package(int index, byte[] data);
    14.         private Dictionary<int, Package> packages;
    15.  
    16.         public void StartMessageHandler()
    17.         {
    18.             packages = new Dictionary<int, Package>();
    19.             packages.Add(1, HandleLogin);
    20.         }
    21.  
    22.         public void HandleData(int index, byte[] data)
    23.         {
    24.             int packageNum;
    25.             Package package;
    26.             ByteBuffer buffer = new ByteBuffer();
    27.             buffer.WriteBytes(data);
    28.             packageNum = buffer.ReadInt();
    29.             buffer = null;
    30.             if (packageNum == 0)
    31.                 return;
    32.             if (packages.TryGetValue(packageNum,out package))
    33.             {
    34.                 package.Invoke(index, data);
    35.             }
    36.         }
    37.  
    38.         private void HandleLogin(int index, byte[] data)
    39.         {
    40.             ByteBuffer buffer = new ByteBuffer();
    41.             buffer.WriteBytes(data);
    42.             buffer.ReadInt();
    43.             string username = buffer.ReadString();
    44.             string password = buffer.ReadString();
    45.  
    46.             // mysql
    47.             if (Database.singleton.AccountExist(username))
    48.             {
    49.                 if (Database.singleton.LogginExist(username,password))
    50.                 {
    51.                     ByteBuffer bufferResponse = new ByteBuffer();
    52.                     bufferResponse.WriteInt(10);
    53.                     bufferResponse.WriteString("Login Sucessfull!");
    54.                     ServerSendData.singleton.SendData(index, bufferResponse.ToArray());
    55.                 }
    56.                 else
    57.                 {
    58.                     ByteBuffer bufferResponse = new ByteBuffer();
    59.                     bufferResponse.WriteInt(11);
    60.                     bufferResponse.WriteString("Password Error!");
    61.                     ServerSendData.singleton.SendData(index, bufferResponse.ToArray());
    62.                 }
    63.             }
    64.             else
    65.             {
    66.                 ByteBuffer bufferResponse = new ByteBuffer();
    67.                 bufferResponse.WriteInt(11);
    68.                 bufferResponse.WriteString("Account Not Exist!");
    69.                 ServerSendData.singleton.SendData(index, bufferResponse.ToArray());
    70.                 return;
    71.             }
    72.        
    73.         }
    74.     }
    75. }
    76.  

    ServerSendData.cs

    Code (CSharp):
    1. using System;
    2.  
    3. using System.Collections.Generic;
    4. using System.Linq;
    5. using System.Text;
    6. using ByteBufferDLL;
    7.  
    8. namespace CalixServer2
    9. {
    10.     class ServerSendData
    11.     {
    12.         public static ServerSendData singleton = new ServerSendData();
    13.  
    14.         public void SendData(int index, byte[] data)
    15.         {
    16.             ByteBuffer buffer = new ByteBuffer();
    17.             buffer.WriteBytes(data);
    18.             Network.clientConnections[index].stream.BeginWrite(buffer.ToArray(), 0, buffer.ToArray().Length, null, null);
    19.             buffer = null;
    20.         }
    21.     }
    22. }
    23.  

    ClientConnection.cs
    Code (CSharp):
    1. using System;
    2.  
    3. using System.Net.Sockets;
    4.  
    5.  
    6. namespace CalixServer2
    7. {
    8.     public class ClientConnection
    9.     {
    10.         public int ID;
    11.         public string IP;
    12.         public TcpClient Socket;
    13.         public NetworkStream stream;
    14.         public byte[] readBuff;
    15.  
    16.        
    17.  
    18.         public void Start()
    19.         {
    20.             Socket.ReceiveBufferSize = 1024;
    21.             Socket.SendBufferSize = 1024;
    22.             stream = Socket.GetStream();
    23.             Array.Resize(ref readBuff, Socket.ReceiveBufferSize);
    24.             stream.BeginRead(readBuff, 0,Socket.ReceiveBufferSize,OnReceiveData,null);
    25.         }
    26.  
    27.         private void OnReceiveData(IAsyncResult result)
    28.         {
    29.             try
    30.             {
    31.                 int readBytes = stream.EndRead(result);
    32.                 if (Socket == null)
    33.                     return;
    34.  
    35.                 if (readBytes <= 0)
    36.                 {
    37.                     CloseConnection();
    38.                     return;
    39.                 }
    40.  
    41.                 byte[] newBytes = null;
    42.                 Array.Resize(ref newBytes, readBytes);
    43.                 Buffer.BlockCopy(readBuff,0,newBytes,0,readBytes);
    44.  
    45.                 ServerHandleData.singleton.HandleData(ID, newBytes);
    46.  
    47.                 if (Socket == null)
    48.                     return;
    49.                 stream.BeginRead(readBuff,0,Socket.ReceiveBufferSize,OnReceiveData,null);
    50.  
    51.             }
    52.             catch (Exception e)
    53.             {
    54.                 CloseConnection();
    55.             }
    56.         }
    57.  
    58.         void CloseConnection()
    59.         {
    60.            
    61.             Socket.Close();
    62.             Socket = null;
    63.             Network.RemoveClientConnection(ID);
    64.         }
    65.     }
    66. }
    67.  

    Network.cs

    Code (CSharp):
    1. using System;
    2.  
    3. using System.Net;
    4. using System.Net.Sockets;
    5. using System.Collections.Generic;
    6. using System.Threading;
    7. using System.Text;
    8. using ByteBufferDLL;
    9.  
    10. namespace CalixServer2
    11. {
    12.     class Network
    13.     {
    14.         private TcpListener serverSocket;
    15.         public static Network singleton = new Network();
    16.         public static List<ClientConnection> clientConnections = new List<ClientConnection>();
    17.  
    18.         public void StartServer()
    19.         {
    20.             serverSocket = new TcpListener(IPAddress.Any, 5500);
    21.             serverSocket.Start();
    22.             serverSocket.BeginAcceptTcpClient(OnClientConnect,null);
    23.             Program.WriteConsole("Server Started Sucessfully!");
    24.         }
    25.  
    26.         private void OnClientConnect(IAsyncResult result)
    27.         {
    28.             TcpClient client = serverSocket.EndAcceptTcpClient(result);
    29.             client.NoDelay = false;
    30.  
    31.             int index = clientConnections.Count;
    32.             var newClient = new ClientConnection();
    33.             newClient.Socket = client;
    34.             newClient.IP = client.Client.RemoteEndPoint.ToString();
    35.             newClient.ID = index+1;
    36.             newClient.Start();
    37.             clientConnections.Add(newClient);
    38.             Program.WriteConsole("Client Connection From: "+newClient.IP + "| ID: "+newClient.ID);
    39.             serverSocket.BeginAcceptTcpClient(OnClientConnect, null);
    40.  
    41.            
    42.  
    43.         }
    44.  
    45.         public  static void RemoveClientConnection(int i)
    46.         {
    47.             clientConnections.RemoveAt(i-1);
    48.         }
    49.     }
    50. }
    51.  
    52.  
     
  2. Deleted User

    Deleted User

    Guest