【问题标题】:How to create TCP message framing for the stream如何为流创建 TCP 消息帧
【发布时间】:2017-11-19 22:11:51
【问题描述】:

这是我的客户端连接到服务器的方式:

using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using UnityEngine.UI;
using System.Net.Sockets;
using System.IO;
using System;
using System.Text.RegularExpressions;
using UnityEngine.SceneManagement;
using Newtonsoft.Json;
using System.Linq;

public class ClientWorldServer : MonoBehaviour {

    public bool socketReady;
    public static TcpClient socket;
    public static NetworkStream stream;
    public static StreamWriter writer;
    public static StreamReader reader;

    public void ConnectToWorldServer()
    {
        if (socketReady)
        {
            return;
        }
        //Default host and port values;
        string host = "127.0.0.1";
        int port = 8080;

        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);
        }

    }
}

这是我使用Send 函数向服务器发送数据的方式:

public void Send(string header, Dictionary<string, string> data)
{

    if (stream.CanRead)
    {
        socketReady = true;
    }

    if (!socketReady)
    {
        return;
    }
    JsonData SendData = new JsonData();
    SendData.header = "1x" + header;
    foreach (var item in data)
    {
        SendData.data.Add(item.Key.ToString(), item.Value.ToString());
    }
    SendData.connectionId = connectionId;

    string json = JsonConvert.SerializeObject(SendData);
    var howManyBytes = json.Length * sizeof(Char);
    writer.WriteLine(json);
    writer.Flush();

    Debug.Log("Client World:" + json);
}

如您所见,我将数据发送到 Stream 就像一个字符串而不是一个字节数组。据我所知,我应该将数据作为字节数组发送到消息大小之前并跟随消息。在服务器端,我不知道如何读取这些数据。

这是我现在的阅读方式(现在可以,但如果我尝试一次发送更多消息,它将无法正常工作):

class WorldServer
{
    public List<ServerClient> clients = new List<ServerClient>();
    public List<ServerClient> disconnectList;


    public List<CharactersOnline> charactersOnline = new List<CharactersOnline>();

    public int port = 8080;
    private TcpListener server;
    private bool serverStarted;

    private int connectionIncrementor;

    private string mysqlConnectionString = @"server=xxx;userid=xxx;password=xxx;database=xx";

    private MySqlConnection mysqlConn = null;
    private MySqlDataReader mysqlReader;

    static void Main(string[] args)
    {
        WorldServer serverInstance = new WorldServer();

        Console.WriteLine("Starting World Server...");

        try
        {
            serverInstance.mysqlConn = new MySqlConnection(serverInstance.mysqlConnectionString);
            serverInstance.mysqlConn.Open();
            Console.WriteLine("Connected to MySQL version: " + serverInstance.mysqlConn.ServerVersion + "\n");
        }
        catch (Exception e)
        {
            Console.WriteLine("MySQL Error: " + e.ToString());
        }
        finally
        {
            if (serverInstance.mysqlConn != null)
            {
                serverInstance.mysqlConn.Close();
            }
        }

        serverInstance.clients = new List<ServerClient>();
        serverInstance.disconnectList = new List<ServerClient>();

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

            serverInstance.StartListening();
            serverInstance.serverStarted = true;


            Console.WriteLine("Server has been started on port: " + serverInstance.port);
        }
        catch (Exception e)
        {
            Console.WriteLine("Socket error: " + e.Message);
        }

        new Thread(() =>
        {
            Thread.CurrentThread.IsBackground = true;
            /* run your code here */
            while (true)
            {
                string input = Console.ReadLine();
                string[] commands = input.Split(':');
                if (commands[0] == "show online players")
                {
                    Console.WriteLine("Showing connections\n");
                    foreach (CharactersOnline c in serverInstance.charactersOnline)
                    {
                        Console.WriteLine("Character name: " + c.characterName + "Character ID: " + c.characterId + "Connection id: " + c.connectionId + "\n");
                    }
                }
                continue;
            }

        }).Start();

        while (true)
        {
            serverInstance.Update();
        }
    }

    private void Update()
    {
        //Console.WriteLine("Call");
        if (!serverStarted)
        {
            return;
        }

        foreach (ServerClient c in clients.ToList())
        {
            // Is the client still connected?
            if (!IsConnected(c.tcp))
            {
                c.tcp.Close();
                disconnectList.Add(c);
                Console.WriteLine(c.connectionId + " has disconnected.");
                CharacterLogout(c.connectionId);
                continue;
                //Console.WriteLine("Check for connection?\n");
            }
            else
            {



                // Check for message from Client.
                NetworkStream s = c.tcp.GetStream();
                if (s.DataAvailable)
                {
                    StreamReader reader = new StreamReader(s, true);
                    string data = reader.ReadLine();

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

                }
                //continue;
            }
        }

        for (int i = 0; i < disconnectList.Count - 1; i++)
        {
            clients.Remove(disconnectList[i]);
            disconnectList.RemoveAt(i);
        }


    }

   private void OnIncomingData(ServerClient c, string data)
    {
        Console.WriteLine(data);
        dynamic json = JsonConvert.DeserializeObject(data);

        string header = json.header;
        //Console.WriteLine("Conn ID:" + json.connectionId);

        string connId = json.connectionId;
        int.TryParse(connId, out int connectionId);

        string prefix = header.Substring(0, 2);

        if (prefix != "1x")
        {
            Console.WriteLine("Unknown packet: " + data + "\n");
        }
        else
        {
            string HeaderPacket = header.Substring(2);
            switch (HeaderPacket)
            {
                default:
                    Console.WriteLine("Unknown packet: " + data + "\n");
                    break;
                case "004":
                    int accountId = json.data["accountId"];
                    SelectAccountCharacters(accountId, connectionId);
                    break;
                case "005":
                    int characterId = json.data["characterId"];
                    getCharacterDetails(characterId, connectionId);
                    break;
                case "006":
                    int charId = json.data["characterId"];
                    SendDataForSpawningOnlinePlayers(charId, connectionId);
                    break;
                case "008":
                    Dictionary<string, string> dictObj = json.data.ToObject<Dictionary<string, string>>();
                    UpdateCharacterPosition(dictObj, connectionId);
                    break;
            }
        }

    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;
        }
    }

    private void StartListening()
    {
        server.BeginAcceptTcpClient(OnConnection, server);
    }

    private void OnConnection(IAsyncResult ar)
    {
        connectionIncrementor++;
        TcpListener listener = (TcpListener)ar.AsyncState;
        clients.Add(new ServerClient(listener.EndAcceptTcpClient(ar)));
        clients[clients.Count - 1].connectionId = connectionIncrementor;
        StartListening();


        //Send a message to everyone, say someone has connected!
        Dictionary<string, string> SendDataBroadcast = new Dictionary<string, string>();
        SendDataBroadcast.Add("connectionId", clients[clients.Count - 1].connectionId.ToString());

        Broadcast("001", SendDataBroadcast, clients, clients[clients.Count - 1].connectionId);
        Console.WriteLine(clients[clients.Count - 1].connectionId + " has connected.");
    }

这就是服务器向客户端发回数据的方式:

    private void Send(string header, Dictionary<string, string> data, int cnnId)
    {
        foreach (ServerClient c in clients.ToList())
        {

            if (c.connectionId == cnnId)
            {
                try
                {
                    //Console.WriteLine("Sending...");
                    StreamWriter writer = new StreamWriter(c.tcp.GetStream());
                    if (header == null)
                    {
                        header = "000";
                    }
                    JsonData SendData = new JsonData();
                    SendData.header = "0x" + header;
                    foreach (var item in data)
                    {
                        SendData.data.Add(item.Key.ToString(), item.Value.ToString());
                    }
                    SendData.connectionId = cnnId;

                    string JSonData = JsonConvert.SerializeObject(SendData);

                    writer.WriteLine(JSonData);
                    writer.Flush();
                    //Console.WriteLine("Trying to send data to connection id: " + cnnId + " data:" + sendData);
                }
                catch (Exception e)
                {
                    Console.WriteLine("Write error : " + e.Message + " to client " + c.connectionId);
                }
            }
        }
    }

这是我的ServerClient 课程:

public class ServerClient
{
    public TcpClient tcp;
    public int accountId;
    public int connectionId;
    public ServerClient(TcpClient clientSocket)
    {
        tcp = clientSocket;
    }
}

您能否告诉我如何修改客户端上的Send 函数以将数据作为字节数组发送,以便我可以创建“TCP 消息帧”以及如何更改服务器上的以下部分:

        foreach (ServerClient c in clients.ToList())
        {
            // Is the client still connected?
            if (!IsConnected(c.tcp))
            {
                c.tcp.Close();
                disconnectList.Add(c);
                Console.WriteLine(c.connectionId + " has disconnected.");
                CharacterLogout(c.connectionId);
                continue;
                //Console.WriteLine("Check for connection?\n");
            }
            else
            {



                // Check for message from Client.
                NetworkStream s = c.tcp.GetStream();
                if (s.DataAvailable)
                {
                    StreamReader reader = new StreamReader(s, true);
                    string data = reader.ReadLine();

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

                }
                //continue;
            }
        }

哪个负责接收服务器上的数据?

是否可以仅从客户端和服务器上更改这些部分并使其继续工作,但这次使用 TCP 消息帧正确?

当然,一旦我了解了这个框架应该是什么样子,我会重新制作客户端上的侦听器和服务器的发送功能。

【问题讨论】:

    标签: c# sockets tcp


    【解决方案1】:

    您的框架已经由 cr/lf 定义 - 所以很多已经存在;您需要做的是保留一个 后台缓冲区 每个流 - 像 MemoryStream 这样的东西可能就足够了,具体取决于您需要扩展多大;那么基本上你想要做的是这样的:

    while (s.DataAvailable)
    {
        // try to read a chunk of data from the inbound stream
        int bytesRead = s.Read(someBuffer, 0, someBuffer.Length);
        if(bytesRead > 0) {
             // append to our per-socket back-buffer
             perSocketStream.Position = perSocketStream.Length;
             perSocketStream.Write(someBuffer, 0, bytesRead);
    
    
             int frameSize; // detect any complete frame(s)
             while((frameSize = DetectFirstCRLF(perSocketStream)) >= 0) {
                  // decode it as text
                  var backBuffer = perSocketStream.GetBuffer(); 
                  string message = encoding.GetString(
                        backBuffer, 0, frameSize);
                  // remove the frame from the start by copying down and resizing
                  Buffer.BlockCopy(backBuffer, frameSize, backBuffer, 0,
                      (int)(backBuffer.Length - frameSize));
                  perSocketStream.SetLength(backBuffer.Length - frameSize);
    
                  // process it
                  ProcessMessage(message);
             }
        }
    }
    

    【讨论】:

    • 我相信这是服务器端的pastebin.com/Whh0WaRV 部分。但是,我应该在客户端上的 Send 函数中进行什么更改,以使数据作为字节数组发送,以预先确定它的大小?还是我应该改变那里的任何东西?
    • 我也不知道如何声明 someBufferperSocketStream ?你从哪里带的?
    • @Tony 就像我说的:你的数据已经被换行符框住了。您不一定需要字节前缀,也不需要更改有关数据格式或客户端的任何内容。至于本地人:someBuffer 只是用作暂存缓冲区的byte[] - 读取时用于所有套接字的单个缓冲区。可能是 1024 或 2048 或 4096 字节。这里的perSocketStream 是每个套接字的MemoryStream - 你如何存储它取决于你 - 可能类似于我在另一个问题中展示的元组技巧。
    猜你喜欢
    • 1970-01-01
    • 2013-04-06
    • 2013-07-01
    • 2017-12-20
    • 2015-03-28
    • 1970-01-01
    • 2016-12-22
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多