asp.net C# socket编程代码
public partial class comservice {
private int maxlink = 100000;
private int currentlinked;
private manualresetevent tcpclientconnected = new manualresetevent(false);
public void start() {
thread thread = new thread(new parameterizedthreadstart(showstat));
thread.isbackground = true;
thread.start();
tcplistener server = new tcplistener(new system.net.ipendpoint(0, 8090));
server.start(100);
tcpclientconnected.reset();
iasyncresult result = server.beginaccepttcpclient(new asynccallback(acceptor), server);
tcpclientconnected.waitone();
}
private void showstat(object o) {
while (true) {
lock (typeof(comservice)) {
console.writeline("当前连接数:" + currentlinked + "/" + maxlink);
}
thread.sleep(2000);
}
}
private void acceptor(iasyncresult o) {
tcplistener server = o.asyncstate as tcplistener;
debug.assert(server != null);
tcpclient client = null;
try {
client = server.endaccepttcpclient(o);
system.threading.interlocked.increment(ref currentlinked);
} catch {
}
iasyncresult result = server.beginaccepttcpclient(new asynccallback(acceptor), server);
if (client == null) {
return;
} else {
thread.currentthread.join();
}
close(client);
}
private void close(tcpclient client) {
if (client.connected) {
client.client.shutdown(socketshutdown.both);
}
client.client.close();
client.close();
system.threading.interlocked.decrement(ref currentlinked);
}
}
}
以下是client的代码:
public class clientpool {
private static list<tcpwork> clients = new list<tcpwork>();
private static int freecount;
private static int workcount;
private static int maxallowed = 2;
private static int minclients = 2;
/// <summary>
/// create new instance
/// </summary>
private clientpool() {
}
private static clientpool instance;
private static readonly object syncinstanceobj = new object();
public static clientpool singleton {
get {
if (instance == null) {
lock (syncinstanceobj) {
if (instance == null) {
instance = new clientpool();
}
}
}
return instance;
}
}
private static readonly object syncobj = new object();
public tcpwork getclient() {
try {
tcpwork work = new tcpwork();
work.connect("127.0.0.1", 8090);
work.lingerstate = new lingeroption(false, 3);
work.iswork = true;
work.expired = false;
workcount++;
lock (syncobj) {
clients.add(work);
}
console.writeline(workcount);
return work;
} catch (exception ex){
console.writeline(ex.message);
return null;
}
}
}
client模拟多线程并发
class program {
static void main(string[] args) {
for (int i = 0; i < 1000; i++) {
threadpool.queueuserworkitem(new waitcallback(work), null);
}
console.readkey();
}
private static void work(object o) {
clientpool.singleton.getclient();
}
}
补充:asp.net教程,基础入门