[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 {
public socket worksocket = null; // client socket.
public const int buffersize = 1024; // size of receive buffer.
public byte[] buffer = new byte[buffersize]; // receive buffer.
public stringbuilder sb = new stringbuilder(); // received data string.
}
public class asynchronoussocketlistener {
// incoming data from client.
public static string data = null;
// 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("/nhit 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 async 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;
}
}
新闻热点
疑难解答
图片精选