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

时间:2015-12-19 16:03:12

标签: c# websocket

我有这个c#class

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

我设法使用以下方式接收客户端消息:

 string msg = DecodeMessage(bytes);

但是如何从服务器向客户端发送消息?

我正在尝试构建一个websocket服务器,但我无法将msg发送回我的客户端

任何帮助?

2 个答案:

答案 0 :(得分:0)

scala> nums.where($"id" isin $"nums").show
org.apache.spark.sql.AnalysisException: cannot resolve '(`id` IN (`nums`))' due to data type mismatch: Arguments must be same type but were: int != array<int>;;
'Filter id#18 IN (nums#19)
+- AnalysisBarrier
      +- Project [_1#15 AS id#18, _2#16 AS nums#19]
         +- LocalRelation [_1#15, _2#16]

答案 1 :(得分:-2)

Sora,我认为这个链接可以帮助您入门: TCP Server/Client Intro

它包含非常简单TCP服务器/客户端的源代码。请注意,在服务器接受套接字后,它会从流中读取,输出该消息,然后继续向该流写入确认。

在客户端:发送消息后,客户端从同一个流中读取字节以获得服务器的确认。