Socket Send and Receive C# c socket receive

This example shows how to send and receive data via TCP/IPusing Socket in .NET Framework. There are methods Socket.Send and Socket.Receive.

Socket.Send method

Send method sends data from your buffer to a connected Socket. When you callthe Send method it returns number of bytes which were ?sent“. But it doesn'tmean that the bytes were already received by the other side, it only means thatthe data were stored in a socket buffer and the socket will be trying to sendthem. If the socket buffer is full a WouldBlock error occurs.You should wait for a while a try to send the dataagain.

Following method sends size bytes stored in the buffer from theoffset position. If the operation lasts more than timeoutmilliseconds it throws an exception.

[C#]

public static void Send(Socket socket, byte[] buffer, int offset, int size, int timeout){ int startTickCount = Environment.TickCount; int sent = 0; // how many bytes is already sent do { if (Environment.TickCount > startTickCount + timeout) throw new Exception("Timeout."); try { sent += socket.Send(buffer, offset + sent, size - sent, SocketFlags.None); } catch (SocketException ex) { if (ex.SocketErrorCode == SocketError.WouldBlock || ex.SocketErrorCode == SocketError.IOPending || ex.SocketErrorCode == SocketError.NoBufferSpaceAvailable) { // socket buffer is probably full, wait and try again Thread.Sleep(30); } else throw ex; // any serious error occurr } } while (sent < size);}

To call the Send method use following code snippet (supposethe static Send method is defined in MyClass class). TCP/IP socket can beobtained using TcpClient class. Use TcpClient.Client property to get the underlying Socket (thisproperty is public since .NET Framework2.0).

[C#]

Socket socket = tcpClient.Client;string str = "Hello world!";try{ // sends the text with timeout 10s MyClass.Send(socket, Encoding.UTF8.GetBytes(str), 0, str.Length, 10000);}catch (Exception ex) { /* ... */ }Socket.Receive method

Receive method receives data from a bound Socket to your buffer. The methodreturns number of received bytes. If the socket buffer is empty aWouldBlock error occurs. You should try to receive thedatalater.

Following method tries to receive size bytes into the buffer tothe offset position. If the operation lasts more than timeoutmilliseconds it throws an exception.

[C#]

public static void Receive(Socket socket, byte[] buffer, int offset, int size, int timeout){ int startTickCount = Environment.TickCount; int received = 0; // how many bytes is already received do { if (Environment.TickCount > startTickCount + timeout) throw new Exception("Timeout."); try { received += socket.Receive(buffer, offset + received, size - received, SocketFlags.None); } catch (SocketException ex) { if (ex.SocketErrorCode == SocketError.WouldBlock || ex.SocketErrorCode == SocketError.IOPending || ex.SocketErrorCode == SocketError.NoBufferSpaceAvailable) { // socket buffer is probably empty, wait and try again Thread.Sleep(30); } else throw ex; // any serious error occurr } } while (received < size);}

Call the Receive method using code such this:

[C#]

Socket socket = tcpClient.Client;byte[] buffer = new byte[12]; // length of the text "Hello world!"try{ // receive data with timeout 10s MyClass.Receive(socket, buffer, 0, buffer.Length, 10000); string str = Encoding.UTF8.GetString(buffer, 0, buffer.Length);}catch (Exception ex) { /* ... */ }

Socket Send and Receive [C#] c socket receive
See also

[C#] Download Files from Web– how todownload files from url to localdisk

[C#] Check Local IP Address– check whether anIP islocal

Socket– MSDN– provides many methods for networkcommunications

Socket.Send– MSDN– sends data to a socket

Socket.Receive– MSDN– receives data fromasocket

SocketError– MSDN– enumeration with error codes forthe Socket (WouldBlock)

TcpClient– MSDN– provides client connectionsforTCP

TcpClient.Client– MSDN– gets theunderlyingSocket

By Jan Slama, 2007

  

爱华网本文地址 » http://www.aihuau.com/a/25101012/111172.html

更多阅读

如何清理C盘的垃圾文件 win8电脑c盘怎么清理

如何清理C盘的垃圾文件?很多网友都会有这样的疑问,那么今天就和大家来分享下如何清理C盘的垃圾文件,请看下文:1、360的小工具里有个软件搬家功能 把你的软件和大的文件都移到其他盘。?2、首先你的C盘空间是多大的,还有你是否经常将软件

VSSVisual SourceSafe 使用方法 visual c 6.0使用方法

VSS(Visual SourceSafe)使用方法——简介Visual SourceSafe简介lVSS微软的产品。简单好用,局域网中用VSS。适用于Team级还可以,企业级不好,仅支持Windows操作系统。?Visual SourceSafe是一个源代码控制系统,可以保存文件的不同版本,可以比

windows网络编程socket) c语言socket网络编程

应用程序创建socket,通过绑定,socket与驱动程序联系,向socket发送的数据通过驱动发到网络。端口号标识在同一台计算机上运行的不同网络程序。1.socket函数SOCKET socket(int af, int type, int protocol)af: 地址族,对于TCP/IP只能是AF_I

linux中socket编程中使用send发送结构体小结 c socket 结构体

客套话不说了:socket中的send函数可以发送字符串,不能直接发送结构体,自己理解:结构体即内存中一段连续的内存,这样send中可以发送结构体指针 上代码:代码功能:客户端发送给服务端一个结构体,服务端返回客户端一字符串客户端代码 client.

声明:《Socket Send and Receive C# c socket receive》为网友情何以堪分享!如侵犯到您的合法权益请联系我们删除