Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- using System;
- using System.Collections;
- using System.Collections.Generic;
- using System.IO;
- using System.Net;
- using System.Net.Sockets;
- using UnityEngine;
- public class Server : MonoBehaviour {
- [SerializeField] int port;
- List<ServerClient> clients;
- List<ServerClient> disconnectList;
- TcpListener server;
- bool serverStarted;
- private void Start()
- {
- clients = new List<ServerClient>();
- disconnectList = new List<ServerClient>();
- try
- {
- server = new TcpListener(IPAddress.Any, port);
- server.Start();
- StartListening();
- serverStarted = true;
- Debug.Log("Server has been started on port " + port);
- }
- catch(System.Exception e)
- {
- Debug.Log("socekt error: " + e.Message);
- }
- }
- private void Update()
- {
- if(!serverStarted)
- {
- return;
- }
- foreach (ServerClient client in clients)
- {
- //is the client still connected
- if(!IsConnected(client.tcp))
- {
- client.tcp.Close();
- disconnectList.Add(client);
- continue;
- }
- //check for message form the client
- else
- {
- NetworkStream networkStream = client.tcp.GetStream();
- if(networkStream.DataAvailable)
- {
- StreamReader reader = new StreamReader(networkStream, true);
- string data = reader.ReadLine();
- if(data !=null)
- {
- OnIncomingData(client, data);
- }
- }
- }
- }
- }
- void OnIncomingData(ServerClient client, string data)
- {
- Debug.Log(client.clientName + "has sent the following message: " + data);
- }
- bool IsConnected(TcpClient client)
- {
- try
- {
- if(client !=null && client.Client != null && client.Client.Connected)
- {
- //true if Listen has been called and a connection is pending;
- if (client.Client.Poll(0,SelectMode.SelectRead) )
- {
- return !(client.Client.Receive(new byte[1], SocketFlags.Peek) == 0);
- }
- return true;
- }
- else
- {
- return false;
- }
- }
- catch
- {
- return false;
- }
- }
- void StartListening()
- {
- server.BeginAcceptTcpClient(AcceptTcpClient, server);
- }
- void AcceptTcpClient(IAsyncResult asyncResult)
- {
- TcpListener listener = (TcpListener)asyncResult.AsyncState;
- clients.Add(new ServerClient(listener.EndAcceptTcpClient(asyncResult)));
- StartListening();
- //send a message to everyone, say someone has connected
- }
- }
- public class ServerClient
- {
- public TcpClient tcp;
- public string clientName;
- public ServerClient(TcpClient clientSocket)
- {
- clientName = "Guest";
- tcp = clientSocket;
- }
- }
Advertisement