sexta-feira, 31 de julho de 2015

Unity socketserver

https://pt.wikipedia.org/wiki/Round-robin
 
using UnityEngine;
using System;
using System.Threading;
using System.IO;
using System.Net;
using System.Net.Sockets;
using System.Collections;

public class socketserver: MonoBehaviour
{
       public int serverPort = 1433;
       public bool useNat = false;
       public string gameName = "testeunity";
       public void startserver()
       {
             if (Network.peerType == NetworkPeerType.Disconnected)
             {
                    //if (GUILayout.Button ("Start Server"))
                    {
                           Network.InitializeServer(32, serverPort, useNat);
                           MasterServer.RegisterHost(gameName, "stuff", "l33t game for all");
                    }
             }
       }
      
       public void stopserver()
       {
             Network.Disconnect();
             MasterServer.UnregisterHost();         
       }
      
       // Refresh hosts
       public void Refreshhosts()
       {
             //if (GUILayout.Button ("Refresh available Servers") || Time.realtimeSinceStartup > lastHostListRequest + hostListRefreshTimeout)
             {
                    MasterServer.RequestHostList (gameName);
                    lastHostListRequest = Time.realtimeSinceStartup;
             }
       }
       private float lastHostListRequest;
            
       void OnFailedToConnectToMasterServer(NetworkConnectionError info)
       {
                    Debug.Log(info);
       }
            
       void OnFailedToConnect(NetworkConnectionError info)
       {
                    Debug.Log(info);
       }
            
       void OnConnectedToServer() {
               Debug.Log("Connected to server");
       }
            
       void OnDisconnectedFromServer(NetworkDisconnection info) {
               if (Network.isServer)
                   Debug.Log("Local server connection disconnected");
               else
                   if (info == NetworkDisconnection.LostConnection)
                       Debug.Log("Lost connection to the server");
                   else
                       Debug.Log("Successfully diconnected from the server");
       }
      
       private int playerCount;
       void OnPlayerConnected(NetworkPlayer player) {
             playerCount++;
           Debug.Log("Player " + playerCount + " connected from " + player.ipAddress + ":" + player.port);
       }
            
       void OnPlayerDisconnected(NetworkPlayer player) {
             playerCount--;
            
           Debug.Log("Clean up after player " + player);
           Network.RemoveRPCs(player);
           Network.DestroyPlayerObjects(player);
       }


    public TcpClient client;

    // This method that will be called when the thread is started
    public void RunClientSocket()
    {
        string data = null;
        data = null;

        // Buffer for reading data
        byte[] bytes = new byte[256];

        // Get a stream object for reading and writing
        NetworkStream stream = client.GetStream();

        int i;

        while (true)
        {
            // Loop to receive all the data sent by the client.
            while ((i = stream.Read(bytes, 0, bytes.Length)) != 0)
            {
                // Translate data bytes to a ASCII string.
                data = System.Text.Encoding.ASCII.GetString(bytes, 0, i);
                Console.WriteLine("Received: {0}", data);


                if (data.IndexOf("\n") > -1)
                {
                    string readed = data.Substring(0, data.IndexOf("\n"));
                    data = data.Substring(data.IndexOf("\n") + 1);
                }

                //                // Process the data sent by the client.
                //                data = data.ToUpper();
                //               
                //               
                //               
                //               
                //                byte[] msg = System.Text.Encoding.ASCII.GetBytes(data);
                //                // Send back a response.
                //                stream.Write(msg, 0, msg.Length);
                //                Console.WriteLine("Sent: {0}", data);           
            }

            //-----------------------
            // write
            //-----------------------                
            string message = "teste";

            // Translate the passed message into ASCII and store it as a Byte array.
            byte[] data2 = System.Text.Encoding.ASCII.GetBytes(message);

            // Get a client stream for reading and writing.
            //  Stream stream = client.GetStream();

            //NetworkStream stream = client.GetStream();

            // Send the message to the connected TcpServer.
            stream.Write(data2, 0, data2.Length);

            Console.WriteLine("Sent: {0}", message);
        }
        // Shutdown and end connection
        client.Close();
    }


    public void DoitASync()
    {
        // Create the thread object, passing in the Alpha.Beta method
        // via a ThreadStart delegate. This does not start the thread.
        Thread oThread = new Thread(new ThreadStart(this.RunClientSocket));

        // Start the thread
        oThread.Start();
    }

}

public class socketlistener
{
    public void StartServer()
    {
        Thread trd = new Thread(new ThreadStart(ServerRunASync));
        //trd.IsBackground = true;
        trd.Start();
    }

    private void ServerRunASync()
    {
        TcpListener server = null;
        try
        {
            // Set the TcpListener on port 13000.
            Int32 port = 13000;
            IPAddress localAddr = IPAddress.Parse("127.0.0.1");

            // TcpListener server = new TcpListener(port);
            server = new TcpListener(localAddr, port);

            // Start listening for client requests.
            server.Start();




            // Enter the listening loop.
            while (true)
            {
                Console.Write("Waiting for a connection... ");

                // Perform a blocking call to accept requests.
                // You could also user server.AcceptSocket() here.
                TcpClient newclient = server.AcceptTcpClient();
                Console.WriteLine("Connected!");



                socketserver clientsok = new socketserver();
                clientsok.client = newclient;
                clientsok.DoitASync();




                //                clientsocketex c = new clientsocketex();
                //                c.client = newclient;
                //                c.RunASync();





            }
        }
        catch (SocketException e)
        {
            Console.WriteLine("SocketException: {0}", e);
        }
        finally
        {
            // Stop listening for new clients.
            server.Stop();
        }


        //       Console.WriteLine("\nHit enter to continue...");
        //       Console.Read();
    }

}


Postar um comentário