[ASP.NET] Using C # Development Socket Communication

xiaoxiao2021-03-06  89

The following example shows how to send data and reception responses to the HTTP server to the HTTP server using the Socket class.

[C #]

Public String DosocketGet (String Server)

{

// sets up variables and a string to write to the server

ENCODING ASCII = Encoding.ASCII;

// If you need to transfer the Chinese string here, you need to set it to encoding.default

String get = "Get / http / 1.1 / r / nhost:" Server

"/ r / nConnection: Close / R / N / R / N";

Byte [] Byteget = ascii.getbytes (GET);

Byte [] recvbytes = new byte [256];

String strretpage = null;

// ipaddress and ipndpoint represent the endpoint tria Will

// receive the request.

// Get The first ipaddress in The List Using DNS.

Ipaddress hostd = dns.resolve (server) .addresslist [0];

IpendPoint Ephost = New IpendPoint (HostAdd, 80);

// Creates The socket for sending data over tcp.

Socket S = New Socket (AddressFamily.InterNetwork, Sockettype.Stream,

Protocoltype.tcp);

// Connects to the host using ipndpoint.

S.Connect (Ephost);

IF (! S.Connected)

{

StrretPage = "Unable to connect to host";

Return StrretPage;

}

// sends the get text to the host.

s.send (byteget, byteget.length); socketflags.none;

// Receives the page, looping unsil alltes are receivated

INT32 bytes = S.Receive (Recvbytes, Recvbytes.length, 0);

StrretPage = "Default HTML Page On" Server ": / r / n";

StrretPage = strretpage ascii.getstring (recvbytes, 0, bytes);

While (bytes> 0)

{

Bytes = S.Receive (Recvbytes, Recvbytes.length; SocketFlags.none);

StrretPage = strretpage ascii.getstring (recvbytes, 0, bytes);

}

// If you want to close the connection immediately, call s.close ();

Return StrretPage;

}

转载请注明原文地址:https://www.9cbs.com/read-96110.html

New Post(0)