c#(Socket)异步套接字代码示例
程序员文章站
2022-06-03 10:58:43
异步客户端套接字示例 下面的示例程序创建一个连接到服务器的客户端。该客户端是用异步套接字生成的,因此在等待服务器返回响应时不挂起客户端应用程序的执行...
异步客户端套接字示例
下面的示例程序创建一个连接到服务器的客户端。该客户端是用异步套接字生成的,因此在等待服务器返回响应时不挂起客户端应用程序的执行。该应用程序将字符串发送到服务器,然后在控制台显示该服务器返回的字符串。
c#
using system;
using system.net;
using system.net.sockets;
using system.threading;
using system.text;
// state object for receiving data from remote device.
public class stateobject {
// client socket.
public socket worksocket = null;
// size of receive buffer.
public const int buffersize = 256;
// receive buffer.
public byte[] buffer = new byte[buffersize];
// received data string.
public stringbuilder sb = new stringbuilder();
}
public class asynchronousclient {
// the port number for the remote device.
private const int port = 11000;
// manualresetevent instances signal completion.
private static manualresetevent connectdone =
new manualresetevent(false);
private static manualresetevent senddone =
new manualresetevent(false);
private static manualresetevent receivedone =
new manualresetevent(false);
// the response from the remote device.
private static string response = string.empty;
private static void startclient() {
// connect to a remote device.
try {
// establish the remote endpoint for the socket.
// the name of the
// remote device is "host.contoso.com".
iphostentry iphostinfo = dns.resolve("host.contoso.com");
ipaddress ipaddress = iphostinfo.addresslist[0];
ipendpoint remoteep = new ipendpoint(ipaddress, port);
// create a tcp/ip socket.
socket client = new socket(addressfamily.internetwork,
sockettype.stream, protocoltype.tcp);
// connect to the remote endpoint.
client.beginconnect( remoteep,
new asynccallback(connectcallback), client);
connectdone.waitone();
// send test data to the remote device.
send(client,"this is a test<eof>");
senddone.waitone();
// receive the response from the remote device.
receive(client);
receivedone.waitone();
// write the response to the console.
console.writeline("response received : {0}", response);
// release the socket.
client.shutdown(socketshutdown.both);
client.close();
} catch (exception e) {
console.writeline(e.tostring());
}
}
private static void connectcallback(iasyncresult ar) {
try {
// retrieve the socket from the state object.
socket client = (socket) ar.asyncstate;
// complete the connection.
client.endconnect(ar);
console.writeline("socket connected to {0}",
client.remoteendpoint.tostring());
// signal that the connection has been made.
connectdone.set();
} catch (exception e) {
console.writeline(e.tostring());
}
}
private static void receive(socket client) {
try {
// create the state object.
stateobject state = new stateobject();
state.worksocket = client;
// begin receiving the data from the remote device.
client.beginreceive( state.buffer, 0, stateobject.buffersize, 0,
new asynccallback(receivecallback), state);
} catch (exception e) {
console.writeline(e.tostring());
}
}
private static void receivecallback( iasyncresult ar ) {
try {
// retrieve the state object and the client socket
// from the asynchronous state object.
stateobject state = (stateobject) ar.asyncstate;
socket client = state.worksocket;
// read data from the remote device.
int bytesread = client.endreceive(ar);
if (bytesread > 0) {
// there might be more data, so store the data received so far.
state.sb.append(encoding.ascii.getstring(state.buffer,0,bytesread));
// get the rest of the data.
client.beginreceive(state.buffer,0,stateobject.buffersize,0,
new asynccallback(receivecallback), state);
} else {
// all the data has arrived; put it in response.
if (state.sb.length > 1) {
response = state.sb.tostring();
}
// signal that all bytes have been received.
receivedone.set();
}
} catch (exception e) {
console.writeline(e.tostring());
}
}
private static void send(socket client, string data) {
// convert the string data to byte data using ascii encoding.
byte[] bytedata = encoding.ascii.getbytes(data);
// begin sending the data to the remote device.
client.beginsend(bytedata, 0, bytedata.length, 0,
new asynccallback(sendcallback), client);
}
private static void sendcallback(iasyncresult ar) {
try {
// retrieve the socket from the state object.
socket client = (socket) ar.asyncstate;
// complete sending the data to the remote device.
int bytessent = client.endsend(ar);
console.writeline("sent {0} bytes to server.", bytessent);
// signal that all bytes have been sent.
senddone.set();
} catch (exception e) {
console.writeline(e.tostring());
}
}
public static int main(string[] args) {
startclient();
return 0;
}
}
异步服务器套接字示例 下面的示例程序创建一个接收来自客户端的连接请求的服务器。该服务器是用异步套接字生成的,
因此在等待来自客户端的连接时不挂起服务器应用程序的执行。该应用程序接收来自客户端的字符串,
在控制台显示该字符串,然后将该字符串回显到客户端。来自客户端的字符串必须包含字符串“<eof>”,
以发出表示消息结尾的信号。
c#
复制代码
using system;
using system.net;
using system.net.sockets;
using system.text;
using system.threading;
// state object for reading client data asynchronously
public class stateobject {
// client socket.
public socket worksocket = null;
// size of receive buffer.
public const int buffersize = 1024;
// receive buffer.
public byte[] buffer = new byte[buffersize];
// received data string.
public stringbuilder sb = new stringbuilder();
}
public class asynchronoussocketlistener {
// thread signal.
public static manualresetevent alldone = new manualresetevent(false);
public asynchronoussocketlistener() {
}
public static void startlistening() {
// data buffer for incoming data.
byte[] bytes = new byte[1024];
// establish the local endpoint for the socket.
// the dns name of the computer
// running the listener is "host.contoso.com".
iphostentry iphostinfo = dns.resolve(dns.gethostname());
ipaddress ipaddress = iphostinfo.addresslist[0];
ipendpoint localendpoint = new ipendpoint(ipaddress, 11000);
// create a tcp/ip socket.
socket listener = new socket(addressfamily.internetwork,
sockettype.stream, protocoltype.tcp );
// bind the socket to the local endpoint and listen for incoming connections.
try {
listener.bind(localendpoint);
listener.listen(100);
while (true) {
// set the event to nonsignaled state.
alldone.reset();
// start an asynchronous socket to listen for connections.
console.writeline("waiting for a connection...");
listener.beginaccept(
new asynccallback(acceptcallback),
listener );
// wait until a connection is made before continuing.
alldone.waitone();
}
} catch (exception e) {
console.writeline(e.tostring());
}
console.writeline("\npress enter to continue...");
console.read();
}
public static void acceptcallback(iasyncresult ar) {
// signal the main thread to continue.
alldone.set();
// get the socket that handles the client request.
socket listener = (socket) ar.asyncstate;
socket handler = listener.endaccept(ar);
// create the state object.
stateobject state = new stateobject();
state.worksocket = handler;
handler.beginreceive( state.buffer, 0, stateobject.buffersize, 0,
new asynccallback(readcallback), state);
}
public static void readcallback(iasyncresult ar) {
string content = string.empty;
// retrieve the state object and the handler socket
// from the asynchronous state object.
stateobject state = (stateobject) ar.asyncstate;
socket handler = state.worksocket;
// read data from the client socket.
int bytesread = handler.endreceive(ar);
if (bytesread > 0) {
// there might be more data, so store the data received so far.
state.sb.append(encoding.ascii.getstring(
state.buffer,0,bytesread));
// check for end-of-file tag. if it is not there, read
// more data.
content = state.sb.tostring();
if (content.indexof("<eof>") > -1) {
// all the data has been read from the
// client. display it on the console.
console.writeline("read {0} bytes from socket. \n data : {1}",
content.length, content );
// echo the data back to the client.
send(handler, content);
} else {
// not all data received. get more.
handler.beginreceive(state.buffer, 0, stateobject.buffersize, 0,
new asynccallback(readcallback), state);
}
}
}
private static void send(socket handler, string data) {
// convert the string data to byte data using ascii encoding.
byte[] bytedata = encoding.ascii.getbytes(data);
// begin sending the data to the remote device.
handler.beginsend(bytedata, 0, bytedata.length, 0,
new asynccallback(sendcallback), handler);
}
private static void sendcallback(iasyncresult ar) {
try {
// retrieve the socket from the state object.
socket handler = (socket) ar.asyncstate;
// complete sending the data to the remote device.
int bytessent = handler.endsend(ar);
console.writeline("sent {0} bytes to client.", bytessent);
handler.shutdown(socketshutdown.both);
handler.close();
} catch (exception e) {
console.writeline(e.tostring());
}
}
public static int main(string[] args) {
startlistening();
return 0;
}
}
下面的示例程序创建一个连接到服务器的客户端。该客户端是用异步套接字生成的,因此在等待服务器返回响应时不挂起客户端应用程序的执行。该应用程序将字符串发送到服务器,然后在控制台显示该服务器返回的字符串。
c#
using system;
using system.net;
using system.net.sockets;
using system.threading;
using system.text;
// state object for receiving data from remote device.
public class stateobject {
// client socket.
public socket worksocket = null;
// size of receive buffer.
public const int buffersize = 256;
// receive buffer.
public byte[] buffer = new byte[buffersize];
// received data string.
public stringbuilder sb = new stringbuilder();
}
public class asynchronousclient {
// the port number for the remote device.
private const int port = 11000;
// manualresetevent instances signal completion.
private static manualresetevent connectdone =
new manualresetevent(false);
private static manualresetevent senddone =
new manualresetevent(false);
private static manualresetevent receivedone =
new manualresetevent(false);
// the response from the remote device.
private static string response = string.empty;
private static void startclient() {
// connect to a remote device.
try {
// establish the remote endpoint for the socket.
// the name of the
// remote device is "host.contoso.com".
iphostentry iphostinfo = dns.resolve("host.contoso.com");
ipaddress ipaddress = iphostinfo.addresslist[0];
ipendpoint remoteep = new ipendpoint(ipaddress, port);
// create a tcp/ip socket.
socket client = new socket(addressfamily.internetwork,
sockettype.stream, protocoltype.tcp);
// connect to the remote endpoint.
client.beginconnect( remoteep,
new asynccallback(connectcallback), client);
connectdone.waitone();
// send test data to the remote device.
send(client,"this is a test<eof>");
senddone.waitone();
// receive the response from the remote device.
receive(client);
receivedone.waitone();
// write the response to the console.
console.writeline("response received : {0}", response);
// release the socket.
client.shutdown(socketshutdown.both);
client.close();
} catch (exception e) {
console.writeline(e.tostring());
}
}
private static void connectcallback(iasyncresult ar) {
try {
// retrieve the socket from the state object.
socket client = (socket) ar.asyncstate;
// complete the connection.
client.endconnect(ar);
console.writeline("socket connected to {0}",
client.remoteendpoint.tostring());
// signal that the connection has been made.
connectdone.set();
} catch (exception e) {
console.writeline(e.tostring());
}
}
private static void receive(socket client) {
try {
// create the state object.
stateobject state = new stateobject();
state.worksocket = client;
// begin receiving the data from the remote device.
client.beginreceive( state.buffer, 0, stateobject.buffersize, 0,
new asynccallback(receivecallback), state);
} catch (exception e) {
console.writeline(e.tostring());
}
}
private static void receivecallback( iasyncresult ar ) {
try {
// retrieve the state object and the client socket
// from the asynchronous state object.
stateobject state = (stateobject) ar.asyncstate;
socket client = state.worksocket;
// read data from the remote device.
int bytesread = client.endreceive(ar);
if (bytesread > 0) {
// there might be more data, so store the data received so far.
state.sb.append(encoding.ascii.getstring(state.buffer,0,bytesread));
// get the rest of the data.
client.beginreceive(state.buffer,0,stateobject.buffersize,0,
new asynccallback(receivecallback), state);
} else {
// all the data has arrived; put it in response.
if (state.sb.length > 1) {
response = state.sb.tostring();
}
// signal that all bytes have been received.
receivedone.set();
}
} catch (exception e) {
console.writeline(e.tostring());
}
}
private static void send(socket client, string data) {
// convert the string data to byte data using ascii encoding.
byte[] bytedata = encoding.ascii.getbytes(data);
// begin sending the data to the remote device.
client.beginsend(bytedata, 0, bytedata.length, 0,
new asynccallback(sendcallback), client);
}
private static void sendcallback(iasyncresult ar) {
try {
// retrieve the socket from the state object.
socket client = (socket) ar.asyncstate;
// complete sending the data to the remote device.
int bytessent = client.endsend(ar);
console.writeline("sent {0} bytes to server.", bytessent);
// signal that all bytes have been sent.
senddone.set();
} catch (exception e) {
console.writeline(e.tostring());
}
}
public static int main(string[] args) {
startclient();
return 0;
}
}
异步服务器套接字示例 下面的示例程序创建一个接收来自客户端的连接请求的服务器。该服务器是用异步套接字生成的,
因此在等待来自客户端的连接时不挂起服务器应用程序的执行。该应用程序接收来自客户端的字符串,
在控制台显示该字符串,然后将该字符串回显到客户端。来自客户端的字符串必须包含字符串“<eof>”,
以发出表示消息结尾的信号。
c#
复制代码
using system;
using system.net;
using system.net.sockets;
using system.text;
using system.threading;
// state object for reading client data asynchronously
public class stateobject {
// client socket.
public socket worksocket = null;
// size of receive buffer.
public const int buffersize = 1024;
// receive buffer.
public byte[] buffer = new byte[buffersize];
// received data string.
public stringbuilder sb = new stringbuilder();
}
public class asynchronoussocketlistener {
// thread signal.
public static manualresetevent alldone = new manualresetevent(false);
public asynchronoussocketlistener() {
}
public static void startlistening() {
// data buffer for incoming data.
byte[] bytes = new byte[1024];
// establish the local endpoint for the socket.
// the dns name of the computer
// running the listener is "host.contoso.com".
iphostentry iphostinfo = dns.resolve(dns.gethostname());
ipaddress ipaddress = iphostinfo.addresslist[0];
ipendpoint localendpoint = new ipendpoint(ipaddress, 11000);
// create a tcp/ip socket.
socket listener = new socket(addressfamily.internetwork,
sockettype.stream, protocoltype.tcp );
// bind the socket to the local endpoint and listen for incoming connections.
try {
listener.bind(localendpoint);
listener.listen(100);
while (true) {
// set the event to nonsignaled state.
alldone.reset();
// start an asynchronous socket to listen for connections.
console.writeline("waiting for a connection...");
listener.beginaccept(
new asynccallback(acceptcallback),
listener );
// wait until a connection is made before continuing.
alldone.waitone();
}
} catch (exception e) {
console.writeline(e.tostring());
}
console.writeline("\npress enter to continue...");
console.read();
}
public static void acceptcallback(iasyncresult ar) {
// signal the main thread to continue.
alldone.set();
// get the socket that handles the client request.
socket listener = (socket) ar.asyncstate;
socket handler = listener.endaccept(ar);
// create the state object.
stateobject state = new stateobject();
state.worksocket = handler;
handler.beginreceive( state.buffer, 0, stateobject.buffersize, 0,
new asynccallback(readcallback), state);
}
public static void readcallback(iasyncresult ar) {
string content = string.empty;
// retrieve the state object and the handler socket
// from the asynchronous state object.
stateobject state = (stateobject) ar.asyncstate;
socket handler = state.worksocket;
// read data from the client socket.
int bytesread = handler.endreceive(ar);
if (bytesread > 0) {
// there might be more data, so store the data received so far.
state.sb.append(encoding.ascii.getstring(
state.buffer,0,bytesread));
// check for end-of-file tag. if it is not there, read
// more data.
content = state.sb.tostring();
if (content.indexof("<eof>") > -1) {
// all the data has been read from the
// client. display it on the console.
console.writeline("read {0} bytes from socket. \n data : {1}",
content.length, content );
// echo the data back to the client.
send(handler, content);
} else {
// not all data received. get more.
handler.beginreceive(state.buffer, 0, stateobject.buffersize, 0,
new asynccallback(readcallback), state);
}
}
}
private static void send(socket handler, string data) {
// convert the string data to byte data using ascii encoding.
byte[] bytedata = encoding.ascii.getbytes(data);
// begin sending the data to the remote device.
handler.beginsend(bytedata, 0, bytedata.length, 0,
new asynccallback(sendcallback), handler);
}
private static void sendcallback(iasyncresult ar) {
try {
// retrieve the socket from the state object.
socket handler = (socket) ar.asyncstate;
// complete sending the data to the remote device.
int bytessent = handler.endsend(ar);
console.writeline("sent {0} bytes to client.", bytessent);
handler.shutdown(socketshutdown.both);
handler.close();
} catch (exception e) {
console.writeline(e.tostring());
}
}
public static int main(string[] args) {
startlistening();
return 0;
}
}
上一篇: Photoshop打造简单的红色羽毛笔