0

I have been try the implementation of the server client on my new project. i have taked from a tutorial and i try to get it work, but then its seems to have a problem on my code boot sides its works but wen i host and i make a client connect it connect to the server and the serer go on the game, but the client stay stuck its not go to the game like i expected. This is my codes: Server

using UnityEngine;
using System.Collections;
using System.Net.Sockets;
using System.Collections.Generic;
using System.Net;
using System;
using System.IO;
public class serverx : MonoBehaviour 
{

public int port = 6321;

private List<serverclient> clients;
private List<serverclient> disconnectList;

private TcpListener server;
private bool serverStarted;

public void init()
{
    DontDestroyOnLoad (gameObject);
    clients = new List<serverclient> ();
    disconnectList = new List<serverclient> ();

    try
    {
        server = new TcpListener(IPAddress.Any, port);
        server.Start();

        StartListening();
        serverStarted = true;
    }
    catch (System.Exception e)
    {
        Debug.Log("socket error: "+ e.Message);
    }
}

private void Update()
{
    if (!serverStarted)
        return;

    foreach (serverclient c in clients) 
    {
        //is the client still connected?
        if (!IsConnected(c.tcp))
        {
            c.tcp.Close();
            disconnectList.Add(c);
            continue;
        }
        else
        {
            NetworkStream s = c.tcp.GetStream();
            if (s.DataAvailable)
            {
                StreamReader reader = new StreamReader(s, true);
                string data = reader.ReadLine();

                if (data != null)
                    OnIncomingData(c, data);
            }
        }
    }

    for (int i = 0; i < disconnectList.Count -1; i++) 
    {
        //tell our player somebody has disconnected
        clients.Remove(disconnectList[i]);
        disconnectList.RemoveAt(i);
    }
}
private void StartListening()
{
    server.BeginAcceptTcpClient (AcceptTcpClient, server);
}

private void AcceptTcpClient(IAsyncResult ar)
{
    TcpListener listener = (TcpListener)ar.AsyncState;

    string allUsers = "";

    serverclient sc = new serverclient (listener.EndAcceptTcpClient (ar));
    clients.Add (sc);

    StartListening ();

    Broadcast ("SWHO|" + allUsers, clients[clients.Count - 1]);

    Debug.Log ("Somebody has connected");
}

private bool IsConnected(TcpClient c)
{
    try
    {
        if (c != null && c.Client != null && c.Client.Connected)
        {
            if(c.Client.Poll(0, SelectMode.SelectRead))
                return !(c.Client.Receive(new byte[1], SocketFlags.Peek) == 0);

            return true;
        }
        else
            return false;
    }
    catch
    {
        return false;
    }
}
//server send
private void Broadcast(string data, List<serverclient> cl)
{
    foreach (serverclient sc in cl) 
    {
        try
        {
            StreamWriter writer = new StreamWriter(sc.tcp.GetStream());
            writer.WriteLine(data);
            writer.Flush ();
        }
        catch (Exception e)
        {
            Debug.Log("write error: " + e.Message);
        }
    }
}
private void Broadcast(string data,serverclient c)
{
    List<serverclient> sc = new List<serverclient>{ c};
    Broadcast (data, sc);
}
//server read
private void OnIncomingData(serverclient c, string data)
{
    Debug.Log ("Server:" + data);
    string[] aData = data.Split ('|');

    switch (aData[0]) 
    {
    case "CWHO":
        c.clientName = aData[1];
        Broadcast("SCNN|" + c.clientName, clients);
        break;
    }
}
}

public class serverclient
{
public string clientName;
public TcpClient tcp;

public serverclient(TcpClient tcp)
{
    this.tcp = tcp;
}
}

client

using UnityEngine;
using System.Collections;
using System.Net.Sockets;
using System.IO;
using System;
using System.Collections.Generic;

public class clientx : MonoBehaviour 
{
public string clientName;
public bool isHost;

private bool socketReady;
private TcpClient socket;
private NetworkStream stream;
private StreamWriter writer;
private StreamReader reader;

private List<GameClient> players = new List<GameClient>();

private void Start()
{
    DontDestroyOnLoad (gameObject);
}

public bool ConnectToServer(string host,int port)
{
    if (socketReady)
        return false;

    try
    {
        socket = new TcpClient(host,port);
        stream = socket.GetStream();
        writer = new StreamWriter(stream);
        reader = new StreamReader(stream);

        socketReady = true;
    }
    catch(Exception e)
    {
        Debug.Log("Socket error " +e.Message);
    }

    return socketReady;
}
private void Update()
{
    if (socketReady) 
    {
        if(stream.DataAvailable)
        {
            string data = reader.ReadLine();
            if(data != null)
                OnIncomingData(data);
        }
    }
}

//send messages to the server
public void send(string data)
{
    if (!socketReady)
        return;
    writer.WriteLine (data);
    writer.Flush ();
}
//read messages from server
private void OnIncomingData(string data)
{
    Debug.Log ("Client:" + data);
    string[] aData = data.Split('|');

    switch (aData [0]) 
    {
    case "SWHO":
        for(int i = 1; i < aData.Length -1; i++)
        {
            UserConnected(aData[i],false);
        }
        send("CWHO|" + clientName + "|" + ((isHost)?1:0).ToString());
        break;
    case "SCNN":
        UserConnected(aData[1],false);
        break;
    }
}

private void UserConnected(string name,bool host)
{
    GameClient c = new GameClient ();
    c.name = name;

    players.Add (c);

    if (players.Count == 2)
        GameManager.Instance.StartGame ();
}

private void OnApplicationQuit()
{
    CloseSocket ();
}

private void OnDisable()
{
    CloseSocket ();
}

private void CloseSocket()
{
    if (!socketReady)
        return;
    writer.Close ();
    reader.Close ();
    socket.Close ();
    socketReady = false;
}
}

public class GameClient
{
public string name;
public bool isHost;
}
  • So, what have you tried to fix in that code? – AgentFire Jan 14 '17 at 10:41
  • so wen i host with the app and i try to connect with client to the host it recognize some one have connected, the host go on game but the client stay stuck. i try to fix this – Mirian Stenberg Jan 14 '17 at 10:52
  • You need to use Thread or async. It will block the main Thread if you use the Update function for tcp stuff. Look at the answer in the duplicated stuff for how to do this. – Programmer Jan 26 '17 at 17:45

0 Answers0