简体   繁体   English

如何连接到TCP套接字,在接收数据之前发送数据进行授权

[英]How to connect to a TCP Socket, send data for authorization before receiving data

I am using Rx to connect to a Socket and receive data. 我正在使用Rx连接到Socket并接收数据。 The issue I have is that after connecting to the Socket I need to send data for authorization before data can be received. 我遇到的问题是,连接到套接字后,需要先发送数据进行授权,然后才能接收数据。

Connection 连接

public static IObservable<Unit> WhenConnected(this Socket socket, IPAddress address, int port)
{
    return Observable.FromAsyncPattern<IPAddress, int>(
        socket.BeginConnect,
        socket.EndConnect)(address, port);
}

Receive Data 接收资料

Won't post all the code but in summary it uses TakeWhile to repeatedly receive bytes from the Begin/End Receive async methods. 不会发布所有代码,但总而言之,它使用TakeWhile从Begin / End Receive async方法重复接收字节。

var receiveData = Observable.FromAsyncPattern
    <byte[], int, int, SocketFlags, int>(socket.BeginReceive, socket.EndReceive);

Question 1: 问题1:

Now my issue is how do I go about constructing my subscription? 现在我的问题是我该如何构建订阅?

var query = from _ in socket.WhenConnected(IPAddress.Parse(_host), _port)
            //need to authorize before receiving data
            from value socket.DataReceived().Repeat()
            select value;

using (query.Subscribe(...

Question 2 问题2

Usually I would send packets of information using a NetworkStream rather than a Socket so would I need to do something completely different? 通常我会使用NetworkStream而不是Socket发送信息包,所以我需要做一些完全不同的事情吗?

The Rxx library has some extension methods that are very helpful for this sort of operation. Rxx库具有一些扩展方法,这些方法对于此类操作非常有帮助。 Inside the StreamExtensions.cs of version 1.3, there is 在版本1.3的StreamExtensions.cs中,有

public static IObservable<byte[]> ReadObservable(this Stream stream, int count)

and

public static IObservable<Unit> WriteObservable(this Stream stream, byte[] buffer, int offset, int count)

which can be used on a network stream. 可以在网络流上使用。 I'm not sure if the following is the best way, but it could be set up as follows: 我不确定以下方法是否是最佳方法,但可以将其设置如下:

NetworkStream networkStream = null;
var setupStreamPlan = Observable
  .When(WhenConnected(...))
  .Then(_ => networkStream = new NetworkStream(socket));
var authorizePlan = Observable
  .When(setupStreamPlan)
  .Then(_ => networkStream.WriteObserable(/*message to write*/);
var listenPlan = Observable
  .When(authorizePlan)
  .Then(_ => networkStream.ReadObservable(10).Repeat());
var constantSizeMessageStream = Observable
  .When(listenPlan)
  .Switch();

EDIT: Allowed for networkStream to be set up 编辑:允许设置networkStream

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

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM