简体   繁体   English

使用tcplistener服务器将消息发送回客户端

[英]sending a message back to client using tcplistener server

i have this c# class 我有这个C#课

using System;
using System.Text;
using System.Text.RegularExpressions;
using System.Security.Cryptography;
using System.Collections.Generic;
using System.Linq;
using System.Threading;

class Server
{
  const string SERVER_IP = "127.0.0.1";
  const int  SERVER_PORT = 9998;
   TcpListener server = new TcpListener(IPAddress.Parse(SERVER_IP), SERVER_PORT);
  public void Start ()
  {
    server.Start();
    Console.WriteLine("Server has started on "+SERVER_IP+":"+SERVER_PORT+".{0}Waiting for a connection...", Environment.NewLine);
    TcpClient client;
    while (true) // Add your exit flag here
    {
        client = server.AcceptTcpClient();
        Socket Socket = new Socket(SocketType.Stream, ProtocolType.Tcp);

        ThreadPool.QueueUserWorkItem(ThreadProc, client);
    }
 }

private void ThreadProc(object obj)
{
    Console.WriteLine("A client connected.");
    TcpClient client = (TcpClient)obj;
    NetworkStream stream = client.GetStream();

    int UnactiveTimePeriod = int.Parse(TimeSpan.FromMinutes(1).TotalMilliseconds.ToString());
    //enter to an infinite cycle to be able to handle every change in stream
    while (true)
    {

        while (!stream.DataAvailable) ;

        Byte[] bytes = new Byte[client.Available];

        stream.Read(bytes, 0, bytes.Length);
        // translate bytes of request to string
        string data = Encoding.UTF8.GetString(bytes);

        if (new Regex("^GET").IsMatch(data)) // Handshaking protocol
        {
            Byte[] response = Encoding.UTF8.GetBytes("HTTP/1.1 101 Switching Protocols" + Environment.NewLine
                + "Connection: Upgrade" + Environment.NewLine
                + "Upgrade: websocket" + Environment.NewLine
                + "Sec-WebSocket-Accept: " + Convert.ToBase64String(
                    SHA1.Create().ComputeHash(
                        Encoding.UTF8.GetBytes(
                            new Regex("Sec-WebSocket-Key: (.*)").Match(data).Groups[1].Value.Trim() + "258EAFA5-E914-47DA-95CA-C5AB0DC85B11"
                        )
                    )
                ) + Environment.NewLine
                + Environment.NewLine);

            stream.Write(response, 0, response.Length);

        }
        else
        {
            string msg = DecodeMessage(bytes);
            Console.WriteLine(msg);

            stream.Flush();
        }
        //Console.WriteLine(ByteToString(bytes));
    }

}



private string DecodeMessage(byte[] bytes)
{
    string incomingData = string.Empty;
    byte secondByte = bytes[1];
    int dataLength = secondByte & 127;
    int indexFirstMask = 2;
    if (dataLength == 126)
        indexFirstMask = 4;
    else if (dataLength == 127)
        indexFirstMask = 10;

    IEnumerable<byte> keys = bytes.Skip(indexFirstMask).Take(4);
    int indexFirstDataByte = indexFirstMask + 4;

    byte[] decoded = new byte[bytes.Length - indexFirstDataByte];
    for (int i = indexFirstDataByte, j = 0; i < bytes.Length; i++, j++)
    {
        decoded[j] = (byte)(bytes[i] ^ keys.ElementAt(j % 4));
    }

    return incomingData = Encoding.UTF8.GetString(decoded, 0, decoded.Length);
  }
}

I managed to receive the client messages using this : 我设法收到使用此客户端消息:

 string msg = DecodeMessage(bytes);

but how can i send a message from the server back to the client ? 但是如何将消息从服​​务器发送回客户端?

i am trying to build a websocket server but i can't manage to send a msg back to my client 我正在尝试构建一个websocket服务器,但是我无法设法将msg发送回我的客户端

Any help ? 有什么帮助吗?

    public void SendString(string str)
    {
         //ns is a NetworkStream class parameter
        //logger.Output(">> sendind data to client ...", LogLevel.LL_INFO);
        try
        {

            var buf = Encoding.UTF8.GetBytes(str);
            int frameSize = 64;

            var parts = buf.Select((b, i) => new { b, i })
                            .GroupBy(x => x.i / (frameSize - 1))
                            .Select(x => x.Select(y => y.b).ToArray())
                            .ToList();

            for (int i = 0; i < parts.Count; i++)
            {
                byte cmd = 0;
                if (i == 0) cmd |= 1;
                if (i == parts.Count - 1) cmd |= 0x80;

                ns.WriteByte(cmd);
                ns.WriteByte((byte)parts[i].Length);
                ns.Write(parts[i], 0, parts[i].Length);
            }

            ns.Flush();
        }
        catch (Exception ex)
        {
            _srv.LogError(">> " + ex.Message);
        }

    }

Sora, I think this link should help get you started: TCP Server/Client Intro Sora,我认为此链接应该可以帮助您入门: TCP Server / Client Intro

It contains source code for a very simple TCP Server/Client. 它包含一个非常简单的TCP Server / Client的源代码。 Notice that after the server Accepts the socket, it reads from the stream, outputs that message, then proceeds to write an Acknowledgement to that stream. 请注意,服务器接受套接字后,它将从流中读取,输出该消息,然后继续向该流写入确认。

On the client-side: After sending it's message, the client reads bytes from the same stream to get the server's acknowledgement. 在客户端:发送消息后,客户端从同一流中读取字节以获取服务器的确认。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

相关问题 从服务器(tcplistener)向客户端(tcpclient)发送消息 - Send message from server (tcplistener) to client (tcpclient) TcpListener客户端保持连接状态,发送多条消息,但服务器仅接收或处理第一条消息 - TcpListener Client stays connected sending multiple messages but server only receives or processes the first message C# 在客户端和服务器上使用 TcpListener - C# Using TcpListener on both Client and Server TCPlistener服务器客户端和客户端服务器(从服务器向客户端发送消息) - TCPlistener server-client and client-server ( send message to client from server) TCPClient 向 TCPListener 发送消息后超时 - TCPClient runs into timeout after sending message to TCPListener C# - Websocket - 将消息发送回客户端 - C# - Websocket - Sending Message Back To Client 使用HTTP格式向客户端/服务器发送XML消息 - Using http format in sending XML message to client/server TcpListener:检测客户端断开连接,而不是客户端暂时不发送任何数据 - TcpListener: Detecting a client disconnect as opposed to a client not sending any data for a while 从服务器向客户端发送异步消息 - Sending asynchronous message from server to client 使用XMPP和c#控制台应用程序发送推送通知,以从客户端将Acknowledgemet返回到服务器 - Sending Push Notification using XMPP with c# console app for getting Acknowledgemet back to server from client
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM