Posted on 2009-02-04 15:49
魔のkyo 阅读(1073)
评论(0) 编辑 收藏 引用
用C++实现的具有跨平台兼容性的ServerSocket,Socket,Thread类原始简易版终于完成了。
在设计上本着易用的角度,完全参照Java.
服务器端多线程测试效果截图
封装后的服务器端代码和Java中很相似,十分简单
#include <iostream>
#include "SocketLib.h"
#include "ThreadLib.h"
using namespace std;
class MyThread: public Thread{
Socket m_sock;
int m_num;
static int s_num;
public:
MyThread(Socket sock){
m_sock=sock;
m_num=++s_num;
}
~MyThread(){
m_sock.close();
}
void run(){
static char buf[1024];
while(m_sock>>buf){
cout<<"Connection "<<m_num<<" : "<<buf<<endl;
}
delete this;//我希望每个MyThread实例run一次然后自销毁
}
};
int MyThread::s_num=0;
int main()
{
ServerSocket lsock(4000);
cout<<"Listenning Port 4000"<<endl;
while(1){
Socket dsock=lsock.accept();
Thread *t=new MyThread(dsock);
t->start();
}
}
客户端更加简单
#include <iostream>
#include "SocketLib.h"
using namespace std;
char buf[1024];
int main()
{
Socket s("127.0.0.1",4000);
cout<<"Connect Established"<<endl;
while(cin>>buf){
s<<buf;
}
}