public void Awake() { instance = this; if (serverIp == null) { // Server: start listening for connections this.isServer = true; listener = new TcpListener(listen_ip: IPAddress.Any, port: Globals.port); listener.Start(); listener.BeginAcceptTcpClient(OnServerConnect, null); } else { // Client: try connecting to the server TcpClient client = new TcpClient(); TcpConnectedClient connectedClient = new TcpConnectedClient(client); clientList.Add(connectedClient); client.BeginConnect(serverIp, Globals.port, (ar) => connectedClient.EndConnect(ar), null); } }
public void Awake() { instance = this; if (serverIp == null) { // Server: start listening for connections Console.WriteLine("Starting Server..."); isServer = true; listener = new TcpListener(localaddr: IPAddress.Any, port: Globals.Port); listener.Start(); listener.BeginAcceptTcpClient(OnServerConnect, null); } else { // Client: try connecting to the server Console.WriteLine("Trying to connect to Server..."); TcpClient client = new TcpClient(); TcpConnectedClient connectedClient = new TcpConnectedClient(client); clientList.Add(connectedClient); client.BeginConnect(serverIp, Globals.Port, (ar) => connectedClient.EndConnect(ar), null); } }
void OnRead(IAsyncResult ar) { int length = stream.EndRead(ar); if (length <= 0) { // Connection closed TCPChat.instance.OnDisconnect(this); return; } string newMessage = System.Text.Encoding.UTF8.GetString(readBuffer, 0, length); TCPChat.messageToDisplay += newMessage + Environment.NewLine; if (TCPChat.instance.isServer) { TCPChat.BroadcastChatMessage(newMessage); } stream.BeginRead(readBuffer, 0, readBuffer.Length, OnRead, null); }
private void OnRead(IAsyncResult ar) { int length = stream.EndRead(ar); if (length <= 0) { // Connection closed TCPChat.instance.OnDisconnect(this); return; } string newMessage = System.Text.Encoding.UTF8.GetString(readBuffer, 0, length); Dashboard.instance.AppendStream(newMessage); if (TCPChat.instance.isServer) { TCPChat.BroadcastChatMessage(newMessage); } stream.BeginRead(readBuffer, 0, readBuffer.Length, OnRead, null); }