本文整理汇总了C++中Listen函数的典型用法代码示例。如果您正苦于以下问题:C++ Listen函数的具体用法?C++ Listen怎么用?C++ Listen使用的例子?那么恭喜您, 这里精选的函数代码示例或许可以为您提供帮助。
在下文中一共展示了Listen函数的20个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于我们的系统推荐出更棒的C++代码示例。
示例1: main
void main(){
CallDll();
SocketStartup();//startup the WSA
Listen();
}
开发者ID:hahnakane,项目名称:junkcode,代码行数:6,代码来源:main.cpp
示例2: sizeof
DWORD CTcpServerSocketHelper::Start(ITcpServerSocketHelper_Event *pEvent,
DWORD dwListenPort/*=0*/,BOOL bReadData/*=TRUE*/)
{
DWORD dwResult = -1;
DWORD threadID = 0;
m_pEvent = pEvent;
m_dwListenPort = dwListenPort;
if (!CreateTcpSocket(TRUE))
{
dwResult = 1;
goto Exit0;
}
BOOL bOpt = TRUE;
::setsockopt (m_Socket, SOL_SOCKET, SO_REUSEADDR, (const char*)&bOpt, sizeof (bOpt));
if (!Bind())
{
dwResult = 2;
goto Exit0;
}
if (!Listen())
{
dwResult = 3;
goto Exit0;
}
m_hTerminateAcceptThreadEvent = ::CreateEvent(NULL, TRUE, FALSE,NULL);
if (!m_hTerminateAcceptThreadEvent)
{
dwResult = 4;
goto Exit0;
}
m_hAcceptThreadHandle = (HANDLE)::CreateThread( NULL, 0,
(LPTHREAD_START_ROUTINE)_AcceptThreadProc, this, 0, &threadID );
if (!m_hAcceptThreadHandle)
{
dwResult = 5;
goto Exit0;
}
if (bReadData)
{
m_hTerminateReadDataThreadEvent = ::CreateEvent(NULL, TRUE, FALSE,NULL);
if (!m_hTerminateReadDataThreadEvent)
{
dwResult = 6;
goto Exit0;
}
m_hReadDataThreadHandle = (HANDLE)::CreateThread( NULL, 0,
(LPTHREAD_START_ROUTINE)_ReadDataThreadProc, this, 0, &threadID );
if (!m_hReadDataThreadHandle)
{
goto Exit0;
}
}
dwResult = 0;
Exit0:
if (0 != dwResult)
{
Stop();
}
if (dwResult == 0)
{
return m_dwListenPort;
}
return (DWORD)-1;
}
开发者ID:windyting126,项目名称:simpleserver,代码行数:76,代码来源:TcpSocketHelper.cpp
示例3: main
// MAIN
int main(int argc, char **argv) {
// Local variables
int pid;
int port;
int listenfd;
int connfd;
struct sockaddr_in clientAddr;
socklen_t clientSize = sizeof(clientAddr);
FILE* logFile;
// gets port number
if(argc == 2) {
port = atoi(argv[1]);
} else {
perror("Invalid arguments.");
exit(1);
}
// opens log file
logFile = fopen("log.txt", "a+");
// creates listen socket
listenfd = listenSocket(port);
// starts listening
Listen(listenfd, LISTENQUEUE);
for ( ; ; ) {
// accepts a connection
connfd = Accept(listenfd, (struct sockaddr *)&clientAddr, &clientSize);
// prints the info
PrintConnectionInfo(clientAddr);
// log
logConnection(logFile, clientAddr);
// fork
if((pid = fork()) == 0) {
// child process closes the listen socket
close(listenfd);
// process
process(connfd, clientAddr);
// child process closes the connection
close(connfd);
// prints info of disconnection
printDisconnectInfo(clientAddr);
// log
logDisconnection(logFile, clientAddr);
// finished execution
exit(0);
}
// parent process closes the connection with client
close(connfd);
}
// closes log file
fclose(logFile);
return(0);
}
开发者ID:betohayasida,项目名称:mc833-2s16,代码行数:68,代码来源:servidor.c
示例4: main
//!! textbook p146 ch 6.11 poll 模板
int
main(int argc, char **argv)
{
int i, maxi, listenfd, connfd, sockfd;
int nready;
ssize_t n;
char buf[MAXLINE];
socklen_t clilen;
struct pollfd client[OPEN_MAX];
struct sockaddr_in cliaddr, servaddr;
listenfd = Socket(AF_INET, SOCK_STREAM, 0);
bzero(&servaddr, sizeof(servaddr));
servaddr.sin_family = AF_INET;
servaddr.sin_addr.s_addr = htonl(INADDR_ANY);
servaddr.sin_port = htons(SERV_PORT);
Bind(listenfd, (SA *) &servaddr, sizeof(servaddr));
Listen(listenfd, LISTENQ);
client[0].fd = listenfd;
client[0].events = POLLRDNORM;
for (i = 1; i < OPEN_MAX; i++)
client[i].fd = -1; /* -1 indicates available entry */
maxi = 0; /* max index into client[] array */
/* end fig01 */
/* include fig02 */
for ( ; ; ) {
nready = Poll(client, maxi+1, INFTIM);
if (client[0].revents & POLLRDNORM) { /* new client connection */
clilen = sizeof(cliaddr);
connfd = Accept(listenfd, (SA *) &cliaddr, &clilen);
#ifdef NOTDEF
printf("new client: %s\n", Sock_ntop((SA *) &cliaddr, clilen));
#endif
for (i = 1; i < OPEN_MAX; i++)
if (client[i].fd < 0) {
client[i].fd = connfd; /* save descriptor */
break;
}
if (i == OPEN_MAX)
err_quit("too many clients");
client[i].events = POLLRDNORM;
if (i > maxi)
maxi = i; /* max index in client[] array */
if (--nready <= 0)
continue; /* no more readable descriptors */
}
for (i = 1; i <= maxi; i++) { /* check all clients for data */
if ( (sockfd = client[i].fd) < 0)
continue;
if (client[i].revents & (POLLRDNORM | POLLERR)) {
if ( (n = read(sockfd, buf, MAXLINE)) < 0) {
if (errno == ECONNRESET) {
/*4connection reset by client */
#ifdef NOTDEF
printf("client[%d] aborted connection\n", i);
#endif
Close(sockfd);
client[i].fd = -1;
} else
err_sys("read error");
} else if (n == 0) {
/*4connection closed by client */
#ifdef NOTDEF
printf("client[%d] closed connection\n", i);
#endif
Close(sockfd);
client[i].fd = -1;
} else
Writen(sockfd, buf, n);
if (--nready <= 0)
break; /* no more readable descriptors */
}
}
}
}
开发者ID:BigR-Lab,项目名称:CodeRes_Cpp,代码行数:87,代码来源:tcpservpoll01.c
示例5: NiListenThread
// Management port Listen thread
void NiListenThread(THREAD *thread, void *param)
{
NAT *n = (NAT *)param;
SOCK *a;
UINT i;
bool b = false;
// Validate arguments
if (thread == NULL || param == NULL)
{
return;
}
// Initialize the management list
n->AdminList = NewList(NULL);
while (true)
{
a = Listen(DEFAULT_NAT_ADMIN_PORT);
if (b == false)
{
b = true;
NoticeThreadInit(thread);
}
if (a != NULL)
{
break;
}
Wait(n->HaltEvent, NAT_ADMIN_PORT_LISTEN_INTERVAL);
if (n->Halt)
{
return;
}
}
n->AdminListenSock = a;
AddRef(a->ref);
// Waiting
while (true)
{
SOCK *s = Accept(a);
THREAD *t;
NAT_ADMIN *admin;
if (s == NULL)
{
break;
}
if (n->Halt)
{
ReleaseSock(s);
break;
}
admin = ZeroMalloc(sizeof(NAT_ADMIN));
admin->Nat = n;
admin->Sock = s;
t = NewThread(NiAdminThread, admin);
WaitThreadInit(t);
ReleaseThread(t);
}
// Disconnect all management connections
LockList(n->AdminList);
{
for (i = 0;i < LIST_NUM(n->AdminList);i++)
{
NAT_ADMIN *a = LIST_DATA(n->AdminList, i);
Disconnect(a->Sock);
WaitThread(a->Thread, INFINITE);
ReleaseThread(a->Thread);
ReleaseSock(a->Sock);
Free(a);
}
}
UnlockList(n->AdminList);
ReleaseList(n->AdminList);
ReleaseSock(a);
}
开发者ID:benapetr,项目名称:SoftEtherVPN,代码行数:82,代码来源:Nat.c
示例6: main
int main(int argc, char **argv)
{
int i, maxi, listenfd, connfd, sockfd;
int nready;
ssize_t n;
char buf[MAXLINE];
socklen_t clilen;
struct pollfd client[OPEN_MAX];
struct sockaddr_in cliaddr, servaddr;
listenfd = Socket(AF_INET, SOCK_STREAM, 0);
bzero(&servaddr, sizeof(servaddr));
servaddr.sin_family = AF_INET;
servaddr.sin_addr.s_addr = htonl(INADDR_ANY);
servaddr.sin_port = htons(SERV_PORT);
Bind(listenfd, (SA *)&servaddr, sizeof(servaddr));
Listen(listenfd, LISTENQ);
client[0].fd = listenfd;
client[0].events = POLLIN;
for (i = 1; i < OPEN_MAX; i++)
client[1].fd = -1;
maxi = 0;
for ( ; ; )
{
nready = Poll(client, maxi + 1, INFTIM);
if (client[0].revents & POLLIN) /* new client connection */
{
clilen = sizeof(cliaddr);
connfd = Accept(listenfd, (SA *)&cliaddr, &clilen);
for (i = 1; i < OPEN_MAX; i++)
if (client[i].fd < 0)
{
client[i].fd = connfd; /* save descriptor */
break;
}
if (i == OPEN_MAX)
err_quit("too many clients");
client[i].events = POLLIN;
if (i > maxi)
maxi = i; /* max index in client[] array */
if (--nready <= 0)
continue; /* no more readable descriptors */
}
for (i = 1; i <= maxi; i++) /* check all clients for data */
{
if ((sockfd = client[i].fd) < 0)
continue;
if (client[i].revents & (POLLIN | POLLERR))
{
if ((n = read(sockfd, buf, MAXLINE)) < 0)
{
if (errno == ECONNRESET) /* connection reset by client */
{
Close(sockfd);
client[i].fd = -1;
}
else
err_sys("read error");
}
else if (n == 0) /* connection closed by client */
{
Close(sockfd);
client[i].fd = -1;
}
else
Writen(sockfd, buf, n);
if (--nready <= 0) /* no more readable descriptors */
break;
}
}
}
}
开发者ID:CanuxCheng,项目名称:UNP1,代码行数:85,代码来源:tcpservpoll.c
示例7: main
/* We can write a simple version of a TCP daytime server, which will work
* with the daytime client.
*
* TCP服务器端一般要执行的步骤是: socket()->填充结构体(协议类型,本机ip地址,
* 本机端口)->bind()->listen()->accept()->使用连接描述符进行读写.
* TCP客户端一般要执行的步骤是: socket()->填充结构体(协议类型,服务器ip地址,
* 服务器已知端口)->connect()
*/
int main(void)
{
int listenfd, connfd;
struct sockaddr_in servaddr;
char buf[BUFSIZ];
time_t ticks;
/* 1. Create a TCP socket */
listenfd = Socket(AF_INET, SOCK_STREAM, 0);
/* 2. Bind server's well-known port to socket
* The server's well-known port (13 for the daytime service) is bound
* to the socket by filling in an Internet socket address structure and
* calling bind(). We specify the IP address as INADDR_ANY, which allows
* the server to accept a client connection on any interface, in case
* the server host has multiple interfaces.
*
* 以普通用户运行该程序时,会报错: bind error: Permission denied
* 此时,错误码是EACCES. 查看man bind手册,对该错误码解释为:
* EACCES The address is protected, and the user is not the superuser.
*
* 在Linux中,只有 root 用户可以绑定 1024 以下的端口.
* 查看 man 7 ip 手册,里面有如下说明:
* The port numbers below 1024 are called privileged ports (or
* sometimes: reserved ports). Only privileged processes (i.e., those
* having the CAP_NET_BIND_SERVICE capability) may bind to these sockets
* 所以运行该程序时,要用root用户或者sudo命令来运行.
* 另外, 13 这个端口可能被占用导致绑定不成功. Linux下,查看端口是否被占
* 用的方法是: netstat -apn | grep <端口号>. 例如: netstat -apn|grep 13
*/
memset(&servaddr, 0, sizeof(servaddr));
servaddr.sin_family = AF_INET;
servaddr.sin_addr.s_addr = htonl(INADDR_ANY);
servaddr.sin_port = htons(13);
Bind(listenfd, (struct sockaddr *)&servaddr, sizeof(servaddr));
/* 3. Convert socket to listening socket
* By calling listen(), the socket is converted into a listening socket,
* on which incomming connections from clients will be accepted by the
* kernel. These three steps, socket(), bind(), and listen(), are the
* normal steps for any TCP server to prepare what we call the listening
* descriptor (listenfd in this example).
*/
Listen(listenfd, LISTENQ);
for (; ;) {
/* 4. Accept client connection, send reply
* Normally, the server process is put to sleep in the call to
* accept(), waiting for a client connection to arrive and be
* accepted. A TCP connection uses what is called a three-way
* handshake to establish a connection. When this handshake
* completes, accept() returns, and the return value from the
* function is a new descriptor (connfd) that is called the
* connected descriptor. This new descriptor is used for
* communication with the new client. A new descriptor is returned
* by accept() for each client that connects to our server.
*/
connfd = Accept(listenfd, NULL, NULL);
/* The current time and date are returned by the library function
* time(), which returns the number of seconds since the Unix
* Eproch: 00:00:00 January 1, 1970, Coordinated Universal Time(UTC)
* The next library function, ctime(), converts this integer value
* into a human-readable string sush as: Mon May 26 20:58:40 2003
*/
ticks = time(NULL);
snprintf(buf, sizeof(buf), "%.24s\r\n", ctime(&ticks));
Write(connfd, buf, strlen(buf));
/* 5. Terminate connection
* The server closes its connection with the client by calling
* close(). This initiates the normal TCP connection termination
* sequence: a FIN is sent in each direction and each FIN is
* acknowledged by the other end.
*/
Close(connfd);
}
return 0;
}
开发者ID:forkhope,项目名称:unp3,代码行数:88,代码来源:daytimesrv.c
示例8: StartListening
//bool CListenSocket::StartListening()
//{
// bListening = true;
//
// // Creating the socket with SO_REUSEADDR may solve LowID issues if emule was restarted
// // quickly or started after a crash, but(!) it will also create another problem. If the
// // socket is already used by some other application (e.g. a 2nd emule), we though bind
// // to that socket leading to the situation that 2 applications are listening at the same
// // port!
// if (!Create(thePrefs.GetPort(), SOCK_STREAM, FD_ACCEPT, CT2CA(theApp.GetBindAddress()), FALSE/*bReuseAddr*/)) // Added by thilon on 2006.10.18, for [BindToAdapter]
// return false;
//
// // Rejecting a connection with conditional WSAAccept and not using SO_CONDITIONAL_ACCEPT
// // -------------------------------------------------------------------------------------
// // recv: SYN
// // send: SYN ACK (!)
// // recv: ACK
// // send: ACK RST
// // recv: PSH ACK + OP_HELLO packet
// // send: RST
// // --- 455 total bytes (depending on OP_HELLO packet)
// // In case SO_CONDITIONAL_ACCEPT is not used, the TCP/IP stack establishes the connection
// // before WSAAccept has a chance to reject it. That's why the remote peer starts to send
// // it's first data packet.
// // ---
// // Not using SO_CONDITIONAL_ACCEPT gives us 6 TCP packets and the OP_HELLO data. We
// // have to lookup the IP only 1 time. This is still way less traffic than rejecting the
// // connection by closing it after the 'Accept'.
//
// // Rejecting a connection with conditional WSAAccept and using SO_CONDITIONAL_ACCEPT
// // ---------------------------------------------------------------------------------
// // recv: SYN
// // send: ACK RST
// // recv: SYN
// // send: ACK RST
// // recv: SYN
// // send: ACK RST
// // --- 348 total bytes
// // The TCP/IP stack tries to establish the connection 3 times until it gives up.
// // Furthermore the remote peer experiences a total timeout of ~ 1 minute which is
// // supposed to be the default TCP/IP connection timeout (as noted in MSDN).
// // ---
// // Although we get a total of 6 TCP packets in case of using SO_CONDITIONAL_ACCEPT,
// // it's still less than not using SO_CONDITIONAL_ACCEPT. But, we have to lookup
// // the IP 3 times instead of 1 time.
//
// //if (thePrefs.GetConditionalTCPAccept() && !thePrefs.GetProxySettings().UseProxy) {
// // int iOptVal = 1;
// // VERIFY( SetSockOpt(SO_CONDITIONAL_ACCEPT, &iOptVal, sizeof iOptVal) );
// //}
//
// if (!Listen())
// return false;
//
// m_port = thePrefs.GetPort();
//
// //// Added by thilon on 2006.10.19, for IFWS - [ICSFirewall]
// //if(thePrefs.GetICFSupport())
// //{
// // bool bResult = (theApp.m_pFirewallOpener->OpenPort(m_port, NAT_PROTOCOL_TCP, EMULE_DEFAULTRULENAME_TCP, thePrefs.GetICFClearOnClose() /*|| thePrefs.GetUseRandomPorts()*/));
// // theApp.QueueLogLine(false, GetResString(bResult ? IDS_FO_TEMPTCP_S : IDS_FO_TEMPTCP_F), m_port);
// //}
//
// if(mapping)
// {
// theApp.RemoveUPnPNatPort(mapping);
// }
//
// if(thePrefs.GetUPnPNat())
// {
// mapping = new CUPnP::UPNPNAT_MAPPING;
// mapping->ref = &mapping;
//
// mapping->internalPort = mapping->externalPort = thePrefs.GetPort();
// mapping->protocol = CUPnP::UNAT_TCP;
// mapping->description = "TCP Port";
// if(theApp.AddUPnPNatPort(mapping, thePrefs.GetUPnPNatTryRandom()))
// thePrefs.SetUPnPTCPExternal(mapping->externalPort);
// }
// /*else
// {
// thePrefs.SetUPnPTCPExternal(thePrefs.GetPort());
// }*/
//
// bListening = true;
// return true;
//}
//upnp_end
bool CListenSocket::StartListening()
{
//ADDED by fengwen on 2007/03/21 <begin> : ·ÀÖ¹Öظ´Create
if (bPortListening)
return true;
//ADDED by fengwen on 2007/03/21 <end> : ·ÀÖ¹Öظ´Create
// Creating the socket with SO_REUSEADDR may solve LowID issues if emule was restarted
// quickly or started after a crash, but(!) it will also create another problem. If the
// socket is already used by some other application (e.g. a 2nd emule), we though bind
// to that socket leading to the situation that 2 applications are listening at the same
// port!
//.........这里部分代码省略.........
开发者ID:kevinzhwl,项目名称:easyMuleVeryCD,代码行数:101,代码来源:ListenSocket.cpp
示例9: main
int
main(int argc, char **argv)
{
int sock_fd,msg_flags;
char readbuf[BUFFSIZE];
struct sockaddr_in servaddr, cliaddr;
struct sctp_sndrcvinfo sri;
struct sctp_event_subscribe evnts;
int stream_increment=1;
socklen_t len;
size_t rd_sz;
if (argc == 2)
stream_increment = atoi(argv[1]);
sock_fd = Socket(AF_INET, SOCK_SEQPACKET, IPPROTO_SCTP);
bzero(&servaddr, sizeof(servaddr));
servaddr.sin_family = AF_INET;
servaddr.sin_addr.s_addr = htonl(INADDR_ANY);
servaddr.sin_port = htons(SERV_PORT);
Bind(sock_fd, (SA *) &servaddr, sizeof(servaddr));
/* include mod_serv06 */
bzero(&evnts, sizeof(evnts));
evnts.sctp_data_io_event = 1;
evnts.sctp_association_event = 1;
evnts.sctp_address_event = 1;
evnts.sctp_send_failure_event = 1;
evnts.sctp_peer_error_event = 1;
evnts.sctp_shutdown_event = 1;
evnts.sctp_partial_delivery_event = 1;
#ifdef UN_MOD
evnts.sctp_adaptation_layer_event = 1;
#else
evnts.sctp_adaption_layer_event = 1;
#endif
Setsockopt(sock_fd, IPPROTO_SCTP, SCTP_EVENTS,
&evnts, sizeof(evnts));
Listen(sock_fd, LISTENQ);
printf("Start waiting...\n");
for ( ; ; ) {
len = sizeof(struct sockaddr_in);
rd_sz = Sctp_recvmsg(sock_fd, readbuf, sizeof(readbuf),
(SA *)&cliaddr, &len,
&sri,&msg_flags);
if(msg_flags & MSG_NOTIFICATION) { // 表示收到一個事件,而非一個資料
print_notification(readbuf);
continue;
}
/* end mod_serv06 */
if(stream_increment) {
sri.sinfo_stream++;
// getsockopt用在sctp有問題!!先跳過!
// if(sri.sinfo_stream >= sctp_get_no_strms(sock_fd,(SA *)&cliaddr, len))
if(sri.sinfo_stream >= 100)
sri.sinfo_stream = 0;
}
Sctp_sendmsg(sock_fd, readbuf, rd_sz,
(SA *)&cliaddr, len,
sri.sinfo_ppid,
sri.sinfo_flags,
sri.sinfo_stream,
0, 0);
}
}
开发者ID:nightfly19,项目名称:renyang-learn,代码行数:66,代码来源:server.c
示例10: MidiInputDevice
MidiInputDeviceMme::MidiInputDeviceMme(std::map<String,DeviceCreationParameter*> Parameters, void* pSampler) : MidiInputDevice(Parameters, pSampler) {
AcquirePorts(((DeviceCreationParameterInt*)Parameters["PORTS"])->ValueAsInt());
if (((DeviceCreationParameterBool*)Parameters["ACTIVE"])->ValueAsBool()) {
Listen();
}
}
开发者ID:svn2github,项目名称:linuxsampler,代码行数:6,代码来源:MidiInputDeviceMme.cpp
示例11: main
int main(int argc, char** argv) {
SOCKET s, s_acceptor; // socket and acceptor socket
struct sockaddr_in saddr, caddr; // server and client address structures
uint16_t lport_n, lport_h; // server port number by htons()
int backlog = 2; // pending requests queue length
socklen_t caddr_len; // client address length
int retValue; // service() returning status
int i;
/* Check number of arguments */
checkArg(argc, 3);
/* The number of children */
n_children = atoi(argv[2]);
if (n_children > 10) {
fprintf(stderr, "- ERROR. Children must be at most 10.\n");
return -1;
}
/* Alloc memory for pids */
pids = (pid_t*)malloc(n_children*sizeof(pid_t));
if (pids == NULL) {
fprintf(stderr, "- ERROR allocating pids.\n");
return -1;
}
/* Instantiate a signal handler for SIGINT */
Signal(SIGINT, sigintHandler);
/* Initialize the socket API (only for Windows) */
SockStartup();
/* Set port number */
lport_n = setPortarg(argv[1], &lport_h);
/* Create the socket */
fprintf(stdout, "Creating the socket...\n");
s = Socket(AF_INET, SOCK_STREAM, IPPROTO_TCP);
fprintf(stdout, "- OK. Socket fd: %d\n", s);
/* Prepare server address structure */
saddr.sin_family = AF_INET;
saddr.sin_port = lport_n;
saddr.sin_addr.s_addr = INADDR_ANY;
/* Bind the socket to a local network address */
fprintf(stdout, "Binding the socket...\n");
Bind(s, (struct sockaddr*) &saddr, sizeof(saddr));
fprintf(stdout, "- OK. Socket bound.\n");
/* Listen to connection requests */
fprintf(stdout, "Listen at socket %d with backlog = %d...\n", s, backlog);
Listen(s, backlog);
fprintf(stdout, "- OK. Socket is listening on ");
showAddress(&saddr);
for (i=0; i<n_children; i++) {
if ((pids[i] = fork()) < 0) {
fprintf(stderr, "- ERROR. fork() failed.\n");
} else if ((pids[i]) > 0) {
// The parent
} else {
// The child
while(1) {
/* Accept connection requests */
br();
caddr_len = sizeof(struct sockaddr_in);
s_acceptor = Accept(s, (struct sockaddr*) &caddr, &caddr_len);
fprintf(stdout, "- New connection from client ");
showAddress(&caddr);
retValue = service(s_acceptor);
closesocket(s_acceptor);
fprintf(stdout, "--- Connection closed by %s", (retValue == 0) ? "client\n" : "server\n");
br();
}
}
}
while(1) {
pause();
}
return 0;
}
开发者ID:ThomasVitale,项目名称:Distributed-Programming-1,代码行数:89,代码来源:server3_3.c
示例12: View
PlayField::PlayField(Hiscore *h, View *parent, ScrollText *st) : View(Rect(0,0,1,1)), Message(){ //-.25f,-.25f,1.25f,1.25f)){
// Listen("/Devices/Input/Dialogic");
SetClearState(false);
#ifdef NEWSCALE
parent->Apply(this);
players = new DynamicArray();
channels = new DynamicArray();
int dir = 0;
int x = 1;
int y = 1;
int xr = 2;
int yb = 2;
int xl = 0;
int yt = 0;
int n = 1;
for(int _x=0; _x<4; _x++){
for(int _y=0; _y<4; _y++){
Player *pl = new Player(h,Rect((float(x)/4.0f),(float(y)/4.0f),(float(x+1)/4.0f),(float(y+1)/4.0f)),st,n++);
Apply(pl);
players->Add(pl);
channels->Add(0);
switch(dir){
case 0: if(++x==xr){ dir++; xr++; } break;
case 1: if(++y==yb){ dir++; yb++; } break;
case 2: if(--x==xl){ dir++; xl--; } break;
case 3: if(--y==yt){ dir=0; yt--; } break;
}
}
}
#else
parent->Apply(this);
players = new DynamicArray();
channels = new DynamicArray();
int dir = 0;
int x = 1;
int y = 1;
int xr = 2;
int yb = 2;
int xl = 1;
int yt = 1;
int n = 1;
for(int _x=0; _x<4; _x++){
for(int _y=0; _y<4; _y++){
Player *pl = new Player(h,Rect((float(x)/4.0f),(float(y)/4.0f),(float(x+1)/4.0f),(float(y+1)/4.0f)),st,n++);
Apply(pl);
players->Add(pl);
channels->Add(0);
switch(dir){
case 0: if(++x==xr){ dir++; xr++; } break;
case 1: if(++y==yb){ dir++; yb++; } break;
case 2: if(--x==xl){ dir++; xl--; } break;
case 3: if(--y==yt){ dir=0; yt--; x--; y--; } break;
}
}
}
#endif
foo = 0;
player_count=0;
zoom = .5f;
xz = yz = 0;
Listen("/Devices/Input/Dialogic");
}
开发者ID:patrickhno,项目名称:bandit,代码行数:69,代码来源:PlayField.cpp
示例13: pthread_create
//.........这里部分代码省略.........
#endif
continue;
}
#ifdef _WIN32
if(s == INVALID_SOCKET) {
if(WSAEWOULDBLOCK != WSAGetLastError()) {
#else
if(s == -1) {
if(errno != EWOULDBLOCK) {
if(errno == EMFILE) { // max opened file descriptors limit reached
sleep(1); // longer sleep give us better chance to have free file descriptor available on next accept call
} else {
#endif
clsEventQueue::mPtr->AddThread(clsEventQueue::EVENT_SRVTHREAD_MSG,
("[ERR] accept() for port "+string(ui16Port)+" has returned error.").c_str());
}
#ifndef _WIN32
}
#endif
} else {
if(isFlooder(s, addr) == true) {
#ifdef _WIN32
shutdown(s, SD_SEND);
closesocket(s);
#else
shutdown(s, SHUT_RDWR);
close(s);
#endif
}
#ifdef _WIN32
::Sleep(1);
#else
nanosleep(&sleeptime, NULL);
#endif
}
} else {
uint32_t iSec = 0;
while(bTerminated == false) {
if(iSuspendTime > iSec) {
#ifdef _WIN32
::Sleep(1000);
#else
sleep(1);
#endif
if(bSuspended == false) {
iSec++;
}
continue;
}
#ifdef _WIN32
EnterCriticalSection(&csServerThread);
#else
pthread_mutex_lock(&mtxServerThread);
#endif
iSuspendTime = 0;
#ifdef _WIN32
LeaveCriticalSection(&csServerThread);
#else
pthread_mutex_unlock(&mtxServerThread);
#endif
if(Listen(true) == true) {
clsEventQueue::mPtr->AddThread(clsEventQueue::EVENT_SRVTHREAD_MSG,
("[SYS] Server socket for port "+string(ui16Port)+" sucessfully recovered from suspend state.").c_str());
} else {
Close();
}
break;
}
}
}
bActive = false;
}
//---------------------------------------------------------------------------
void ServerThread::Close() {
bTerminated = true;
#ifdef _WIN32
closesocket(server);
#else
shutdown(server, SHUT_RDWR);
close(server);
#endif
}
//---------------------------------------------------------------------------
void ServerThread::WaitFor() {
#ifdef _WIN32
WaitForSingleObject(threadHandle, INFINITE);
#else
if(threadId != 0) {
pthread_join(threadId, NULL);
threadId = 0;
}
#endif
}
开发者ID:NIT-Warangal,项目名称:LibSys,代码行数:101,代码来源:ServerThread.cpp
示例14: main
int main(void)
{
unsigned int sockaddr;
unsigned char mysocket;
unsigned int rsize;
/* Initialize the UART for ATmega168 96008N1 */
uart_init();
stdout = &uart_stdout; //Required for printf init
mysocket = 0; // magic number! declare the socket number we will us
sockaddr = W5100_SKT_BASE(mysocket); // calc address of W5100 register set for this socket
puts("AVR Ethernet\r\n");
/*
* Initialize the ATmega168 SPI subsystem
*/
CS_PORT |= (1 << CS_BIT); // pull CS pin high
CS_DDR |= (1 << CS_BIT); // now make it an output
SPI_PORT = SPI_PORT | (1 << PORTB2); // make sure SS is high
SPI_DDR = (1 << PORTB3) | (1 << PORTB5) | (1 << PORTB2); // set MOSI, SCK and SS as output, others as input
SPCR = (1 << SPE) | (1 << MSTR); // enable SPI, master mode 0
SPSR |= (1 << SPI2X); // set the clock rate fck/2
/*
* Load up the callback block, then initialize the Wiznet W5100
*/
my_callbacks._select = &my_select; // callback for selecting the W5100
my_callbacks._xchg = &my_xchg; // callback for exchanging data
my_callbacks._deselect = &my_deselect; // callback for deselecting the W5100
my_callbacks._reset = &my_reset; // callback for hardware-reset of the W5100
W51_register(&my_callbacks); // register our target-specific W5100 routines with the W5100 library
W51_init(); // now initialize the W5100
/*
* Configure the W5100 device to handle PING requests.
* This requires configuring the chip, not a specific socket.
*/
W51_config(&my_cfg); // config the W5100 (MAC, TCP address, subnet, etc
puts("Debug: AVR Ethernet after W5100 config\r\n");
/*
* The main loop. Control stays in this loop forever, processing any received packets
* and sending any requested data.
*/
while (1) {
switch (W51_read(sockaddr + W5100_SR_OFFSET)) // based on current status of socket...
{
case W5100_SKT_SR_CLOSED: // if socket is closed...
if (OpenSocket(mysocket, W5100_SKT_MR_TCP, HTTP_PORT) == mysocket) // if successful opening a socket...
{
Listen(mysocket);
_delay_ms(1);
}
break;
case W5100_SKT_SR_ESTABLISHED: // if socket connection is established...
rsize = ReceivedSize(mysocket); // find out how many bytes
if (rsize > 0) {
if (Receive(mysocket, buf, rsize) != W5100_OK)
break; // if we had problems, all done
/*
* Add code here to process the payload from the packet.
*
* For now, we just ignore the payload and send a canned HTML page so the client at least
* knows we are alive.
*/
strcpy_P((char *)buf,PSTR("HTTP/1.0 200 OK\r\nContent-Type: text/html\r\nPragma: no-cache\r\n\r\n"));
strcat_P((char *)buf,PSTR("<html>\r\n<body>\r\n"));
strcat_P((char *)buf,PSTR("<title>Title</title>\r\n"));
strcat_P((char *)buf,PSTR("<p>Hello world</p>\r\n"));
strcat_P((char *)buf,PSTR("</body>\r\n</html>\r\n"));
if (Send(mysocket, buf, strlen((char *)buf)) == W5100_FAIL) break; // just throw out the packet for now
DisconnectSocket(mysocket);
} else // no data yet...
{
_delay_us(10);
}
break;
case W5100_SKT_SR_FIN_WAIT:
case W5100_SKT_SR_CLOSING:
case W5100_SKT_SR_TIME_WAIT:
case W5100_SKT_SR_CLOSE_WAIT:
case W5100_SKT_SR_LAST_ACK:
CloseSocket(mysocket);
break;
}
}
return 0;
}
开发者ID:billygr,项目名称:avr-ethernet-w5100,代码行数:97,代码来源:avrethernet.c
示例15: Listen
void BaseServer::StartWeb(int port)
{
m_ServWebSock.sockfd = Listen(port);
m_ServWebSock.portno = port;
if(m_ServWebSock.sockfd > 0){
FD_SET(m_ServWebSock.sockfd,&m_setWebSock);
if(m_iWebMaxSock < m_ServWebSock.sockfd)
m_iWebMaxSock = m_ServWebSock.sockfd;
cout<<GetSystemTime()<<": Web交互端口 "<<dec<<port<<" 开启成功."<<endl;
}
else{
cout<<GetSystemTime()<<": "<<port<<" 端口开启失败,程序退出."<<endl;
exit(1);
}
int clnt_sock;
struct sockaddr_in clnt_addr;
socklen_t clnt_addr_size = sizeof(clnt_addr);
memset(&clnt_addr,0,sizeof(clnt_addr));
fd_set tempsets;
struct timeval timeout;
timeout.tv_sec = 5;
timeout.tv_usec = 0;
int result = 0;
size_t buflen = MAXPACKLEN;
char buf[MAXPACKLEN] = {0};
while(true)
{
FD_ZERO(&tempsets);
tempsets = m_setWebSock;
timeout.tv_sec = 5;
timeout.tv_usec = 0;
result = select(m_iWebMaxSock+1,&tempsets,NULL,NULL,&timeout);
if(result > 0)
{
if(FD_ISSET(m_ServWebSock.sockfd,&tempsets))
{
clnt_sock = accept(m_ServWebSock.sockfd,(struct sockaddr*)&clnt_addr,&clnt_addr_size);
if(clnt_sock != -1)
{
if(m_bIsConnWeb){
FD_CLR(m_ClntWebSock.sockfd,&m_setWebSock);
close(m_ClntWebSock.sockfd);
}
m_ClntWebSock.sockfd = clnt_sock;
FD_SET(m_ClntWebSock.sockfd,&m_setWebSock);
if(m_iWebMaxSock < m_ClntWebSock.sockfd)
m_iWebMaxSock = m_ClntWebSock.sockfd;
m_ClntWebSock.portno = m_ServWebSock.portno;
memcpy(m_ClntWebSock.ipaddr,inet_ntoa(clnt_addr.sin_addr),16);
m_bIsConnWeb = true;
#ifndef NO_DEBUG
cout<<GetSystemTime()<<": Web Client Connected "<<m_ClntWebSock.ipaddr<<endl;
#endif
}
}
if(m_bIsConnWeb)
{
if(FD_ISSET(m_ClntWebSock.sockfd,&tempsets))
{
while(true)
{
memset(buf,0,buflen);
int len = recvn(m_ClntWebSock.sockfd,buf,buflen);
if(len == 6)
{
if((buf[0]&0xFF) == 0xAA && (buf[1]&0xFF) == 0xAA)
{
/********************添加获取站点信息及截止时间功能***************************/
g_logs.WriteLog("收到采集数据截止日期更新命令.");
pthread_mutex_lock(&m_infoMutex);
iTimeSpace = GetConfigureFromDatabase();
if(iTimeSpace == -1)
{
char space[4] = {0};
#ifndef NO_DEBUG
cout<<"获取数据库截止日期配置失败,从本地读取"<<endl;
#endif
g_logs.WriteLog("获取数据库截止日期配置失败,从本地读取.");
GetConfigureString("TIMESPACE",space,4,"30");
iTimeSpace = atoi(space);
}
pthread_mutex_unlock(&m_infoMutex);
cout<<"超过此截止天数的数据不再接收:"<<dec<<iTimeSpace<<" 天"<<endl;
g_logs.WriteLog("超过此截止天数的数据不再接收:%d",iTimeSpace);
/***************************************************** */
}
}
else if(len == 0)
{
FD_CLR(m_ClntWebSock.sockfd,&m_setWebSock);
close(m_ClntWebSock.sockfd);
cout<<GetSystemTime()<<": Web Client DisConnect "<<m_ClntWebSock.ipaddr<<endl;
m_bIsConnWeb = false;
break;
}
//.........这里部分代码省略.........
开发者ID:steelsoulsjx,项目名称:workspace,代码行数:101,代码来源:server.cpp
示例16: main
int main (void){
char * req = NULL;
char mess[BUFFSIZE];
char * data = NULL;
char file[MAX_FILE_SIZE];
int sockNum = 0, recSock = 0;
int i = 0;
int rc=0, rcr = 0;
int accepted = 0;
int cs=0;
int chunkiterator = 0;
int offset= 0;
struct sockaddr_in from;
socklen_t fromlen;
FILE * fp = NULL;
int bytecounter = 0;
while(1){
req = NULL;
for(i = 0; i < BUFFSIZE ; i++) mess[i] = 0;
data = NULL;
for(i = 0; i < MAX_FILE_SIZE ; i++) file[i] = 0;
sockNum = 0;
recSock = 0;
i = 0;
rc=0;
rcr = 0;
accepted = 0;
cs=0;
chunkiterator = 0;
offset= 0;
fromlen = 0;
fp = NULL;
bytecounter = 0;
//build the request string
req = buildReq(NUMCHUNKS, DATAPORT, FILENAME);
//report request
printf("sent request for \"%s\" in %d chunks over port %d\n", FILENAME, NUMCHUNKS, DATAPORT);
//initialize buffers
//open socket
sockNum = Open("localhost", 11708);
if (DEBUG) fprintf(stderr, "Socket Open\n");
//start listening for response
recSock = Listen(DATAPORT);
//send the request
rc = send( sockNum , req , (strlen(&req[4])+ 4) , 0 ) ;
printf( "Sent %d\n%s\n" , rc , req ) ;
//clean up
free(req);
req = NULL;
close(sockNum);
//start loop for each connection
for (chunkiterator = 0; chunkiterator < NUMCHUNKS; chunkiterator++){
//initialize variables
for(i = 0; i < BUFFSIZE ; i++) mess[i] = 0;
accepted = 0;
offset =0;
//try to accept a connection
while (!accepted){
if (DEBUG) fprintf(stderr, "trying to accept connection. accepted = %d\n", accepted);
fromlen = sizeof(from);
cs = accept( recSock , (struct sockaddr *)&from , &fromlen );
if (DEBUG) fprintf(stderr, "cs = %d\n", cs);
//if it failed, report it
//if it succeeded, raise tthe flafg
if (cs == -1){
perror("accept:");
}else{
(accepted = 1);
}
}
if (DEBUG) fprintf(stderr, "done accepting. cs = %d\n", cs);
do {
//cleart buffer
if (DEBUG) fprintf(stderr, "clearing buffer\n");
for(i = 0; i < BUFFSIZE ; i++) mess[i] = 0;
//read from the socket into the buffer
rc = recv( cs , &mess , sizeof(mess) , 0 ) ;
if (DEBUG) fprintf(stderr, "finished reading %d bytes from socket. offset is currently %d\n", rc, offset);
if (rc == -1)
perror("recv");
//if something was in fact read
if (rc){
//.........这里部分代码省略.........
开发者ID:hoylemd,项目名称:C,代码行数:101,代码来源:lysander.c
示例17: main
int main()
{
int Listenfd,connfd;
socklen_t clilen;
struct sockaddr_in cliaddr, servaddr;
int val,len;
pthread_t recv_thread, send_thread,getinfo_thread;
int res;
Listenfd = Socket(AF_INET,SOCK_STREAM,0);
val = 1;
len = sizeof(int);
Setsockopt(Listenfd, SOL_SOCKET, SO_REUSEPORT,(void *)&val, len);
memset(&servaddr,0,sizeof(servaddr));
servaddr.sin_family = AF_INET;
servaddr.sin_addr.s_addr = htonl(INADDR_ANY);
servaddr.sin_port = htons(SERV_PORT);
Bind(Listenfd,(SA*)&servaddr,sizeof(servaddr));
Listen(Listenfd,LISTENQ);
for( ; ;){
val = 1;
len = sizeof(int);
Setsockopt(Listenfd, SOL_SOCKET, SO_DEBUG,(void *)&val, len);
//sleep(8);
clilen = sizeof(cliaddr);
connfd = Accept(Listenfd,(SA*)&cliaddr,&clilen);
openflag=1;
res = pthread_create(&getinfo_thread, NULL, get_info, (void *)(&connfd));
if (res != 0)
{
perror("Thread creation failed!");
exit(EXIT_FAILURE);
}
res = pthread_create(&recv_thread, NULL, recv_function, (void *)(&connfd));
if (res != 0)
{
perror("Thread creation failed!");
exit(EXIT_FAILURE);
}
res = pthread_create(&send_thread, NULL, send_function, (void *)(&connfd));
if (res != 0)
{
perror("Thread creation failed!");
exit(EXIT_FAILURE);
}
//sleep(200);
//printf("close\n");
//交由系统回收关闭文件描述符
//Close(connfd);
}
return 0;
}
开发者ID:lybxin,项目名称:LNP,代码行数:67,代码来源:tcpserver.c
示例18: main
int main (int argc, char **argv) {
int listenfd, connfd, n;
struct sockaddr_in servaddr, clientaddr;
//char buf[MAXDATASIZE];
char recvline[MAXLINE + 1];
//time_t ticks;
char error[MAXLINE + 1];
//para obter o endereço do socket
socklen_t addrlen = sizeof(clientaddr);
//valor temporario para o id dos processos filhos
pid_t child_pid;
if (argc != 3) { //caso o usuário não tenha fornecido um IP e a porta para conexão
strcpy(error,"uso: ");
strcat(error,argv[0]);
strcat(error," <Porta> <listen Backlog value");
perror(error);
exit(1);
}
//Inicializa o socket
listenfd = Socket(AF_INET, SOCK_STREAM, 0);
//Preenche informacoes relativas ao socket do servidor
Servaddr(&servaddr, argv[1]);
//Associa socket com um ip e uma porta
Bind(listenfd, &servaddr);
//Diz para o socket ouvir conexoes
Listen(listenfd, atoi(argv[2]));
//Registra funcao de handler
Signal(SIGCHLD, sig_child);
//Prepara arquivo de log
time_t now;
char timeString[256];
FILE *log;
while (1){
//Retarda a remoção dos sockets da fila de conexões completas
sleep(10);
//Aceita uma conexao e atribui a um socket
if ((connfd = Accept(listenfd, &clientaddr, &addrlen)) < 0){
if (errno = EINTR){
continue;
}
else{
err_sys("accept error");
}
}
//Registra conexao
time(&now);
strftime (timeString, 256, "%Y-%m-%d %H:%M:%S", localtime(&now));
log = fopen("log.txt","a");
if (log == NULL){
printf ("Failed to log entry.\n");
}
else{
fprintf(log,"[%s] %s:%u conectou-se\n",
timeString,
inet_ntoa(clientaddr.sin_addr),
ntohs(clientaddr.sin
|
请发表评论