27. april 2006 - 00:45
#6
jeg lavede det her eksempel i marts for at illustere teknikken (det er ikke
production ready kode, men du bør kunne få nogle ideer):
#include <iostream>
#include <cstdio>
#include <cstdlib>
#include <cstring>
using namespace std;
#include <windows.h>
const char *WELCOME="Welcome\r\n";
const char *QUIT="quit\r\n";
const char *BYEBYE="Bye bye\r\n";
const char *UNKNOWN="Unknown command\r\n";
const char *NEWLINE="\r\n";
DWORD __stdcall client(void *p)
{
int sd2=*((int*)p);
send(sd2,WELCOME,strlen(WELCOME),0);
char buf[80];
memset(buf,0x00,sizeof(buf));
int ix=0;
int len;
while((len=recv(sd2,buf+ix,sizeof(buf)-ix,0))>0)
{
ix=ix+len;
if(strstr(buf,NEWLINE)!=NULL)
{
char cmd[80];
memset(cmd,0x00,sizeof(cmd));
int cmdlen = (strstr(buf,NEWLINE)-buf)+strlen(NEWLINE);
memmove(cmd,buf,cmdlen);
memmove(buf,buf+cmdlen,ix-cmdlen);
ix=ix-cmdlen;
memset(buf+ix,0x00,sizeof(buf)-ix);
if(strcmpi(cmd,QUIT)==0)
{
send(sd2,BYEBYE,strlen(BYEBYE),0);
closesocket(sd2);
cout << "Client disconnected" << endl;
break;
}
else
{
send(sd2,UNKNOWN,strlen(UNKNOWN),0);
}
}
}
return 0;
}
const int MAXCLI=10;
int main()
{
WSADATA WSAData;
WSAStartup(0x0101,&WSAData);
int sd=socket(AF_INET,SOCK_STREAM,0);
if(sd<0)
{
cout << "Could not create socket: " << strerror(errno) << endl;
}
int status;
struct sockaddr_in local;
local.sin_family=AF_INET;
local.sin_port = htons(1234);
local.sin_addr.s_addr = INADDR_ANY;
status=bind(sd,(struct sockaddr *)&local,sizeof(local));
if(status<0)
{
cout << "Could not bind socket: " << strerror(errno) << endl;
}
status=listen(sd,5);
if(status<0)
{
cout << "Could not listen to socket: " << strerror(errno) << endl;
}
int sd2[MAXCLI];
int n=0;
while(1)
{
sd2[n]=accept(sd,0,0);
if(sd2[n]<0)
{
cout << "Could not accept socket: " << strerror(errno) << endl;
}
cout << "Client connected" << endl;
DWORD id;
CreateThread(0, 0, client, (LPVOID)&sd2[n], 0, &id);
n=(n+1)%MAXCLI;
}
closesocket(sd);
WSACleanup();
return 0;
}
20. juni 2006 - 20:36
#13
Jeg tror arne mente om en af os, som jeg går ud fra skal have point, skulle lægge et.
Anyway ;) Jeg skal ingen have, ellers tak.