private void TryRead() { if (!_isReading) { try { if (Socket.IsDataAvailable()) { _isReading = true; Socket.AsyncReceive(ReadBuffer, 0, ReadBuffer.Length, ServerReadCallBack); } } catch { PendingTermination = true; } } }
/// <summary> /// Initalize Server chat relay, possible message: /// First Byte : Send/Receive chat message /// Second Byte : From server/client /// Rest : The text from the chat /// </summary> /// <param name="server"></param> internal void InitializeChatRelay(object server) { TcpListener listener = server as TcpListener; TcpClient client = listener.AcceptTcpClient(); TcpSocket terrariaSocket = new TcpSocket(client); ISocket chatRelay = terrariaSocket as ISocket; Dimlibs.Instance.Logger.Info("Chat initializing"); while (true) { if (chatRelay.IsConnected()) { if (listener.Pending()) { TcpClient newClient = listener.AcceptTcpClient(); IPEndPoint endpoint = newClient.Client.RemoteEndPoint as IPEndPoint; if (endpoint.Address.Equals(IPAddress.Parse("127.0.0.1"))) { localServer.Add(newClient); } else { otherPlayer.Add(newClient); } } if (chatRelay.IsDataAvailable()) { byte[] data = new byte[ushort.MaxValue]; _socket.AsyncReceive(data, 0, ushort.MaxValue, new SocketReceiveCallback(Netplay.Connection.ClientReadCallBack)); using (MemoryStream stream = new MemoryStream(data)) { using (BinaryReader reader = new BinaryReader(stream)) { byte playerID = reader.ReadByte(); } } } } } }
private void ServerLoop(object context) { TcpListener listener = context as TcpListener; TcpClient client = listener.AcceptTcpClient(); TcpSocket terrariaSocket = new TcpSocket(client); ISocket socket = terrariaSocket as ISocket; Console.WriteLine("server loop started"); RemoteServer server = new RemoteServer(); server.Socket = terrariaSocket; while (false) { try { if (socket.IsConnected()) { if (socket.IsDataAvailable()) { client.GetStream().Flush(); byte[] data = new byte[ushort.MaxValue]; using (MemoryStream stream = new MemoryStream(data)) { BinaryWriter writer = new BinaryWriter(stream); socket.AsyncSend(writer.BaseStream.ReadAllBytes(), 0, 256, new SocketSendCallback(Netplay.Connection.ClientWriteCallBack), null); } } } } catch (Exception e) { Console.WriteLine(e); } } listener.Stop(); Console.WriteLine("server loop stopped"); }