在C#中的同一套接字上发送+接收数据 [英] Sending + Receiving Data on same socket in C#

查看:47
本文介绍了在C#中的同一套接字上发送+接收数据的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试使用套接字(System.Net.Socket,甚至尝试过TcpListener/Client/Etc.)以在等待或已经发送数据时侦听数据.

I'm trying to use a socket (System.Net.Socket, even tried TcpListener/Client/Etc.) to be able to listen for data, while it's waiting to or already sending data.

我已完成以下操作:

    public byte[] bytesIn;
    public byte[] bytesOut;
    public Socket transmitter;
    public Socket receiver;

    public Comlink(String ipAddress, int portNum) 
    {

        try
        {
            IPEndPoint remoteEP = new IPEndPoint(IPAddress.Parse(ipAddress), 11000);

            transmitter = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp);
            transmitter.Listen(10);

            receiver = transmitter.Accept();
            receiver.Receive(bytesIn);

            try
            {
                transmitter.Connect(remoteEP);
                this.bytesOut = Encoding.ASCII.GetBytes("<SYNCUP>");
                int bytesSent = transmitter.Send(this.bytesOut);
                this.connected = true;
            }
        }  // (Omitted my exception handling.)
    }

Receive()函数:

The Receive() function:

this.bytesIn = new byte[1024];
Socket receiver = transmitter.Accept();
int bytesReceived = receiver.Receive(this.bytesIn);

绑定它的代码:

while(comlink.connected)
{
    comlink.Receive();
    handlePacket(comlink.bytesIn);
}

我不确定自己是否使用了正确的过程来接收数据,因为这一直是.NET的抱怨.我需要处理传入的数据.

I'm just not entirely sure if I'm using the right process to receive data, as that's always been the complaint from .NET. I need data to be handled as it comes in.

类似两条路:可以自由输入数据(程序不必移回Receive()并等待数据),就可以对其进行处理.数据也可以从客户端自由地移动到服务器.我知道TCP套接字是双向的,但是我需要改进此类,以便享受自由开放的道路的全部好处.

Something like a two-way street: Data can freely come in (without the program having to move back to Receive() and wait for the data), it gets handled. Data can move freely from the client and to the server, as well. I know TCP sockets are bidirectional, but I need to improve this class so that I can enjoy the full benefits of having a free, open road.

推荐答案

仅显示的代码至少有两件事是错误的.首先,应该使用套接字来侦听或连接到远程套接字,但不能同时使用两者.坦白说,我很惊讶.NET在代码已经进入侦听模式后尝试调用Connect()时,它没有引发异常.

There are at least two things wrong with just the code you show. First, your socket should be used to listen, or to connect to a remote socket, but not both. Frankly, I'm surprised .NET doesn't throw an exception when code tries to call Connect() after it's already been put into listening mode.

第二,您只需要接受一次连接.在每次调用Receive()之前接受都是错误的,这将导致您的代码仅从与其连接的每个套接字接收第一个缓冲区的数据.

Second, you only need to accept a connection once. Accepting before each call to Receive() is wrong and will cause your code to only receive the first buffer's worth of data from each socket that is connected to it.

通常,基于Socket的实现将需要一个服务器"和一个客户端".请注意,一旦建立连接,角色就不必保持如此牢固的建立.但是至关重要的是它们必须处于起步阶段.

In general, your Socket-based implementation will require a "server" and a "client". Note that once the connection is established, the roles do not need to remain so firmly established. But it's critical that they are at the start.

服务器将创建一个新的监听"套接字.使用此套接字,它将接受"来自客户端的连接请求,该过程将创建实际上用于通信的 new 套接字.

The server will create a new "listening" socket. With this socket, it will "accept" connection requests from clients, a process which will create a new socket that is actually used for communication.

我重申:服务器的原始套接字从未用于通过连接进行实际通信.只是用于创建连接的套接字.

I reiterate: the server's original socket is never used for actually communicating over a connection. It's simply the socket that's used to create connections.

客户端将创建一个套接字.使用此套接字,它将尝试连接"到服务器的套接字.建立连接后,该相同套接字将用于实际通信.

The client will create a single socket. With this socket, it will attempt to "connect" to the server's socket. Once the connection is established, that same socket is then used for the actual communication.

您注意到,TCP连接是双向的.因此,一旦建立了连接,服务器和客户端就可以分别使用其单个套接字进行连接以发送和接收数据.当然,请注意,在单线程代码中,您不能同时执行两个操作.因此,要么您的高级协议需要是一种呼叫响应样式的协议,在该协议中,每个端点都可以准确地知道何时需要发送或接收数据,而不必同时执行这两个操作,或者您需要使用.NET为套接字提供了一种异步API,因此您可以同时处理发送和接收.

As you note, TCP connections are bidirectional. So once the connection is established, the server and client can each use their single socket for the connection to both send and receive data. Noting, of course, that in single-threaded code you can't do both at the same time. So either your high-level protocol needs to be a call-and-response style protocol where each end knows precisely when it needs to either send or receive data, and it never needs to do both at the same time, or you need to use one of the asynchronous APIs .NET provides for Sockets, so that you can handle sending and receiving at the same time.

MSDN具有相当不错的Socket编程示例.您应该从这里开始.

MSDN has reasonably decent Socket programming examples. You should start there.

很久以前(无论如何,这在Internet上都是这样)),我写了一系列博客文章来尝试帮助人们开始使用.NET Socket编程.这是我抽空寻找写作时间的最后一件事.您可以考虑将其检查出来,以防对您有帮助: http://blogs.msmvps.com/duniho/2008/08/19/basic-network-programming-in-net/

A long time ago (in Internet years anyway :) ), I wrote a series of blog posts to try to help people get started in .NET Socket programming. It's one of the few things I ever wound up finding the time to write; you might consider checking it out in case it is helpful to you: http://blogs.msmvps.com/duniho/2008/08/19/basic-network-programming-in-net/

这篇关于在C#中的同一套接字上发送+接收数据的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆