Пример #1
0
int main(int argc, const char *argv[])
{
    void *context = zmq_ctx_new();

    assert(argc == 4);
    void *subWildcardSock = createSocket(context, argv[1], ZMQ_SUB);
    void *pubFilenamesSock = createSocket(context, argv[2], ZMQ_PUB);
    void *subDoneSock = createSocket(context, argv[3], ZMQ_SUB);

    std::cout << "Sockets connected" << std::endl;

    bool done = false;
    std::vector<void*> sockets;
    sockets.push_back(subWildcardSock);
    sockets.push_back(subDoneSock);
    while (!done)
    {
        switch (demultiplexSockets(sockets))
        {
        case 0:
            processWildcards(subWildcardSock, pubFilenamesSock);
            break;
        case 1:
            processDone(subDoneSock);
            done = true;
            break;
        };
    }

    zmq_close(subWildcardSock);
    zmq_close(pubFilenamesSock);
    zmq_close(subDoneSock);
}
Пример #2
0
NetworkSocket::NetworkSocket(const ENetworkProtocols Protocol) :
    Protocol_   (Protocol       ),
    Socket_     (INVALID_SOCKET )
{
    createSocket();
    setupBehavior();
}
/******************************************
 * Initialisieren und starten des Servers
 */
void* handleServer(){
  #ifdef _DEBUG
  fprintf(stderr,"++ handleserver\n");
  #endif
  char    bOK         = TRUE;
  int     sProxyClient= ~0,
          sProxyWait  = ~0;
  struct  sockaddr_in saAddress;
  struct  threadParam *pThreadParam;

  if(!generateProxyAddress(&saAddress))             return NULL;
  if(!createSocket        (&sProxyWait))            return NULL;
  if(!bindSocket          (&sProxyWait,&saAddress)) return NULL;
  if(!listenSocket        (&sProxyWait))            return NULL;

  //Endlos-schleife fuer accepts
  while(1){
    bOK=acceptSocket(sProxyWait,&sProxyClient);
    if(bOK==TRUE){
      #ifdef _DEBUG
      fprintf(stderr,"***threadNewClient %d\n",sProxyClient);
      #endif
      pThreadParam=(struct threadParam*)malloc(sizeof(struct threadParam));
      pThreadParam->socketID=sProxyClient;
      threadNewClient((void*)pThreadParam);
    }
  }
  closesocket(sProxyWait);

  #ifdef _DEBUG
  fprintf(stderr,"-- handleserver\n");
  #endif
}
/*************************************************************
   This function creates datagram sockets for
   all routers directly connected to this router (input argument)

   Populates the neighborSocketArray   
   When done, static variable count contains the number of neighbor routers
   stored in the array
   Returns a pointer to the neighborSocketArray
**************************************************************/
neighborSocket* createConnections(char* routerName)
{
	int i,j;
	int socket;
	char *sourcehost, *desthost;
	int port, sourceport, destport;

	if (count != 0)
	{
		return neighborSocketArray;
	}

	// Find details for routerName from routerInfoTable
	for(i=0;i<routercount;i++)
	{
		if(strcmp(routerName,routerInfoTable[i].router) == 0)
			break;
	}

	// Get source hostname for routerName
	sourcehost = (char*)malloc(strlen(routerInfoTable[i].host)+1);
	strcpy(sourcehost,routerInfoTable[i].host);

	// Getbaseport for routerName
	port = routerInfoTable[i].baseport;

	// For all routers directly connected to me (present in linkInfoTable)
	for(i=0;i<linkcount;i++)
	{
		// Find details for this connected router
		for(j=0;j<routercount;j++)
		{
			if(strcmp(linkInfoTable[i].router,routerInfoTable[j].router) == 0)
				break;
		}

		// Get the destination host name
		desthost = (char*)malloc(strlen(routerInfoTable[j].host)+1);
		strcpy(desthost,routerInfoTable[j].host);

		// Calculate destination port number (destination baseport + remotelink)
		destport = routerInfoTable[j].baseport + linkInfoTable[i].remotelink;

		// Calculate source port number (source baseport + locallink)
		sourceport = port + linkInfoTable[i].locallink;

		// Create connected Datagram socket and get socket descriptor
		socket = createSocket(sourcehost, sourceport, desthost, destport);
		
		// Store neighbor router name and socket descriptor in neighborSocketArray
		neighborSocketArray[count].neighbor = (char*)malloc(strlen(linkInfoTable[i].router)+1);
		strcpy(neighborSocketArray[count].neighbor,linkInfoTable[i].router);
		neighborSocketArray[count].socket = socket;

		// Increment the neighborSocket Pair count
		count++;
	}

	return neighborSocketArray;
}
Пример #5
0
/* readURL(url) - access to the specified URL and stores the info read in 'data_URL' variable
 *
 * This function access to the specified URL and stores the info read in 'data_URL' variable
 *
 * It modifies 'flag' if expected answer is not received after sending a command to GPRS module
 *
 * It stores in 'socket_ID' the TCP session ID assigned to the last call to create a socket
 *
 * Returns '1' on success and '0' if error
*/
uint8_t WaspGPRS::readURL(const char* url)
{
	char command[30];
	char* data=",20";
	uint8_t answer=0;
	long previous=0;
	uint8_t byteIN=0;
	uint8_t a=0;
	
	if(!configureGPRS()) return 0;
	
	if(!createSocket(url,"80",GPRS_CLIENT)) return 0;
	
	serialFlush(PORT_USED);
	sprintf(command,"%s%c%c","GET / HTTP/1.0",'\r','\n');
	if(!sendData(command,socket_ID)){
		closeSocket(socket_ID);
		return 0;
	}
		
	waitForData("+KTCP_DATA:",20,0,0);
	if(readData(socket_ID,GPRS_DATA_LENGTH)<0){
		closeSocket(socket_ID);
		return 0;
	}
	
	while(!closeSocket(socket_ID)) closeSocket(socket_ID);
	
	return 1;
}
Пример #6
0
void ServerCore::sendCommandToDevice(QString deviceUID, QVariantMap paramMap)
{
	QTcpSocket *socket = createSocket(deviceUID);

	QObject::connect(socket, &QTcpSocket::readyRead, [=]
	{
		QByteArray byteArray = socket->readAll();
		QJsonDocument jsonDoc = QJsonDocument::fromJson(byteArray);
		QJsonObject jsonObj = jsonDoc.object();

		if (jsonObj[JSON_KEY_STATUS].toInt() == STATUS_SUCCESSFUL)
		{
			QVariantMap retMap = jsonObj.toVariantMap();
			Q_EMIT commandReturned(deviceUID, retMap);
		}

		socket->disconnectFromHost();
	});

	QObject::connect(socket, &QTcpSocket::disconnected, [=]
	{
		socket->deleteLater();
	});

	QString jsonCmd = JsonGenerator::GenerateJsonCommand(TCP_COMMAND_TYPE::SEND_COMMAND_TO_DEVICE, paramMap);

	socket->write(jsonCmd.toLatin1());

	socket->waitForBytesWritten();
	socket->waitForReadyRead();
}
Пример #7
0
echoServerContext *createTcpServer(epoller *epoll, int port) {
	int s;
	struct sockaddr_in sa;

	if ((s = createSocket()) == -1) {
		oom("socket creation error : %s", strerror(errno));
		return NULL;
	}

	memset(&sa, 0, sizeof(sa));
	sa.sin_family = AF_INET;
	sa.sin_port = htons(port);
	sa.sin_addr.s_addr = htonl(INADDR_ANY);

	if (bind(s, (struct sockaddr*)&sa, sizeof(sa)) == -1) {
		close(s);
		oom("bind error : %s", strerror(errno));
		return NULL;
	}
	if (listen(s, 511) == -1) { /* the magic 511 constant is from nginx */
		close(s);
		oom("listen error : %s", strerror(errno));
		return NULL;
	} 

	echoServerContext *server = (echoServerContext *)malloc(sizeof(echoServerContext));
	memset(server, 0, sizeof(echoServerContext));
	
	server->port = port;
	server->epoll = epoll;
	server->serverfd = s;
	return server;
}
Пример #8
0
/*
 * Constructor
 */
CUdpSock::CUdpSock( bool logging ) :
	CSock( logging ),
	_Bound( false )
{
	// Socket creation
	createSocket( SOCK_DGRAM, IPPROTO_UDP );
}
Пример #9
0
void ServerCore::queryDeviceDisplayInfo(QString deviceUID)
{
	QTcpSocket *socket = createSocket(deviceUID);

	QObject::connect(socket, &QTcpSocket::readyRead, [=]
	{
		QByteArray byteArray = socket->readAll();
		QJsonDocument jsonDoc = QJsonDocument::fromJson(byteArray);
		QJsonObject jsonObj = jsonDoc.object();

		if (jsonObj[JSON_KEY_STATUS].toInt() == STATUS_SUCCESSFUL)
		{
			QVariantMap retMap = jsonObj.toVariantMap();
			Q_EMIT displayInfoRecieved(deviceUID, retMap);
		}

		socket->disconnectFromHost();
	});

	QObject::connect(socket, &QTcpSocket::disconnected, [=]
	{
		socket->deleteLater();
	});

	QVariantMap paramMap;
	paramMap.insert(JSON_KEY_SEQ, 1234);

	QString jsonCmd = JsonGenerator::GenerateJsonCommand(TCP_COMMAND_TYPE::QUERY_DEVICE_DISPLAY_INFO, paramMap);

	socket->write(jsonCmd.toLatin1());
}
Пример #10
0
evutil_socket_t
ccnet_net_open_tcp (const struct sockaddr *sa, int nonblock)
{
    evutil_socket_t s;
    int sa_len;

    if( (s = createSocket(sa->sa_family, nonblock)) < 0 )
        return -1;

#ifndef WIN32
    if (sa->sa_family == AF_INET)
        sa_len = sizeof (struct sockaddr_in); 
    else
        sa_len = sizeof (struct sockaddr_in6);
#else
    if (sa->sa_family == AF_INET)
        sa_len = sizeof (struct sockaddr_in); 
    else
        return -1;
#endif


    if( (connect(s, sa, sa_len) < 0)
#ifdef WIN32
        && (sockerrno != WSAEWOULDBLOCK)
#endif
        && (sockerrno != EINPROGRESS) )
    {
        evutil_closesocket(s);
        s = -1;
    }

    return s;
}
Пример #11
0
int main ()
{
    logFile = new std::ofstream;
    (*logFile).open("client_tester.log", std::ios_base::app);


    testerAddr.sin_family = AF_INET;
    testerAddr.sin_port = (uint16_t) port;
    socklen_t addressLength = sizeof(sockaddr_in);
    memset(&testerAddr, 0, addressLength);

    // create bind and listen on socket
    createSocket();
    bindSocket();
    listenSocket();

    // get few commands and print them to log file and stdout?
    std::cout << "waiting to accept connection..." << std::endl;
    commandSocketFD = accept(testerSocketFD, reinterpret_cast<struct sockaddr *>(&cliAddr), &addressLength);
    ssize_t readSize = read(commandSocketFD, buff, MAX_BUFFER_LENGTH);
    std::cout << "buff: " << buff << std::endl;

    // send responses

}
Пример #12
0
/* Listen for incomoing connection from the client accpets 
 * only a maximum of 10 connections */
void setupListenSocket(int port, int *listen_socket) {
  struct sockaddr_in address;
  createServerAddrStruct(&address, port);
  createSocket(listen_socket);
  bindSocket(&address, listen_socket);
  listen(*listen_socket, MAX_PENDING_CONNECTIONS);
}
Пример #13
0
static int tcpGenericConnect(char *err, char *addr, int port, int flags) {
    int s;
    struct sockaddr_in sa;

    if ((s = createSocket(err, PF_INET)) == -1) {
        return -1;
    }
    sa.sin_family = PF_INET;/*{{{*/
    sa.sin_port = htons(port);
    if (inet_aton(addr, &sa.sin_addr) == 0) {
        struct hostent *he;
        he = gethostbyname(addr);
        if (he == NULL) {
            setError(err, "can't resolve: %s", addr);
            close(s);
            return -1;
        }
        memcpy(&sa.sin_addr, he->h_addr, sizeof(struct in_addr));
    }
    if (flags & NETWORK_CONNECT_NONBLOCK) {
        if(setNonBlock(err, s) != 0) {
            return -1;
        }
    }
    if (connect(s, (struct sockaddr*)&sa, sizeof(sa)) == -1) {
        if (errno == EINPROGRESS && (flags & NETWORK_CONNECT_NONBLOCK)) {
            return s;
        }
        setError(err, "connect: %s", strerror(errno));
        close(s);
        return -1;
    }/*}}}*/
    return s;
}
static void sessionHandler(int port)
{
	struct sockaddr_in childSocket;
	socklen_t socketLen = sizeof(childSocket);
	int idx1, clientIdx;

	signal(SIGCHLD, sessionSignalHandler); /* register for the child's signal */
	if(createSocket(port) == 1)
	{
		fprintf(stderr, "sessionHandler: Unable to setup socket\n");
		exit(1);
	}

	while((clientIdx = accept(serverSocket, (struct sockaddr *)&childSocket, &socketLen)) > 0)
	{
		printf("sessionHandler: Client connection from %s, client index %d\n", inet_ntoa(childSocket.sin_addr), clientIdx);
		for(idx1=0; idx1 < MaxSessions; idx1++)
		{
			if(childPID[idx1] == 0)
			{
				serverPID[idx1] = clientIdx;
				childPID[idx1] = createChildProcess(socketService, clientIdx);
				break;
			}
		}

		if(idx1 == MaxSessions)
			fprintf(stderr, "sessionHandler: Max clients reached\n");

		socketLen = sizeof(childSocket);
	}
	shutdown(serverSocket, SHUT_RDWR);
	close(serverSocket);
}
Пример #15
0
int CSocketClient::start(int nSocketType, const char* cszAddr, short nPort,
		int nStyle)
{
	if (AF_UNIX == nSocketType)
	{
		setDomainSocketPath(cszAddr);
	}
	else if (AF_INET == nSocketType)
	{
		if (-1 == setInetSocket(cszAddr, nPort))
		{
			_DBG("set INET socket address & port fail");
			return -1;
		}
	}

	if (-1 != createSocket(nSocketType, nStyle))
	{
		if (SOCK_STREAM == nStyle)
		{
			if (-1 == connectServer())
			{
				socketClose();
				return -1;
			}
		}

		_DBG("[Socket Client] Socket connect success");
		return getSocketfd();
	}

	return -1;
}
Пример #16
0
void Udp::initAddr(u_short port, const std::string& ip) {
  close(sock_);
  memset(&addr_, 0, sizeof(addr_));
  createSocket();

  port_ = port;
  ip_ = ip;

  bool is_host = ip_.empty();

  addr_.sin_family = AF_INET;
  addr_.sin_port = htons(port_);
  
  addr_.sin_addr.s_addr
    = is_host
    ? INADDR_ANY
    : inet_addr(ip_.c_str());

  int on = 1;
  setsockopt(sock_, SOL_SOCKET, SO_REUSEADDR, &on, sizeof(on));

  // named the socket(bind)
  if (is_host) {
    int res = bind(sock_, (sockaddr*)&addr_, sizeof(addr_));
    if (res < 0) {
      std::cout << res << ": err bind" << std::endl;
    }
  }
}
Пример #17
0
int main(int argc, char *argv[]) {
  int listenfd, connectfd;
  struct sockaddr_in host_addr, pin_addr;
  int pin_addr_size;
  pthread_t multiCS;
  ADDR_ARG *arg = NULL;

  createSocket(&listenfd, 0);
  initHostAddr(&host_addr, myport);

  printf(" init ipaddress: %s\n", inet_ntoa(host_addr.sin_addr));
  bindPort(&listenfd, &host_addr);
  listenPort(&listenfd);

  pin_addr_size = sizeof(pin_addr);
  while (1) {
    getAccept(&listenfd, &connectfd, &pin_addr, &pin_addr_size);

    arg = (ADDR_ARG *)malloc(sizeof(ADDR_ARG));
    arg->connectfd = connectfd;
    memcpy((void *)&arg->cli_addr, &pin_addr, sizeof(pin_addr));

    createPthread(&multiCS, start_talk, arg);
  }

  close(listenfd);
  return 0;
}
GdbInOutSocket::GdbInOutSocket() :
   GdbInOut(),
   activeSocket(-1) {

   // Create socket to listen on
   listenSocket = createSocket(GDB_PORT_NUM, true);
}
Пример #19
0
bool SessionManager::init(int argc, char *argv[])
{
	srand(time(&curTime));

	option.load(argc, argv);

	if (!initDB())
		return false;

	s2s->connect(option.s2s_ip, option.s2s_port, 30);

	if (!createSocket(SOCK_STREAM))
		return false;

	if (!bindAddress(option.sm_ip, option.sm_port)) {
		ICQ_LOG("Can not bind on port %d\n", option.sm_port);
		return false;
	}

	listen(sockfd, 5);
	addEvent(SOCKET_READ);

	ICQ_LOG("sm is now started\n");
	return true;
}
Пример #20
0
/*
 * initExpprocSocket()
 *
 * Creates the listen socket for communication to Expproc fro other processes
 *
 * instead of signal handler etc, this routine create a thread to handle the accept
 * thus removing the need for socketfuncs.c and asyncIO.c
 *
 *    Author greg Brissey 3/12/2006
 */
int initExpprocSocket()
{
	int	status, ival;
	int	applPort;
        void *AcceptConnection( void *arg);

	pApplSocket = createSocket( SOCK_STREAM );
	if (pApplSocket == NULL)		/* each call to program in */
	  return( -1 );				   /* sockets.c sets errno */
	ival = openSocket( pApplSocket );
	if (ival != 0)
	  return( -1 );
	ival = bindSocketAnyAddr( pApplSocket );
	if (ival != 0)
        {
	  errLogSysRet(ErrLogOp,debugInfo,"initExpprocSocket: bindSocketAnyAddr failed:" );
	  return( -1 );
         }
	applPort = returnSocketPort( pApplSocket );
	ival = listenSocket( pApplSocket );
	if (ival != 0)
        {
	  errLogSysRet(ErrLogOp,debugInfo,"initExpprocSocket: listenSocket failed:" );
	  return( -1 );
         }


 	 savePortInfo( applPort ); 
         pAcceptQueue = rngBlkCreate(128,"AcceptQ", 1);  /* accepted socket queue */

        /* create thread to handle the accept */
        status = pthread_create (&AcceptThreadId, NULL, AcceptConnection, (void*) pApplSocket);
	return( 0 );

}
Пример #21
0
int
deliverMessage( char *interface, char *message )
{
	char		tmpstring[ 256 ];
	int		ival1, ival2;
	int		ival, mlen;
	MSG_Q_ID	tmpMsgQ;

	if (interface == NULL)
	  return( -1 );
	if (message == NULL)
	  return( -1 );
	mlen = strlen( message );
	if (mlen < 1)
	  return( -1 );

    	ival = sscanf( interface, "%s %d %d\n", &tmpstring[ 0 ], &ival1, &ival2 );

    /*
     *       diagPrint(debugInfo,"Expproc deliverMessage  ----> host: '%s', port: %d,(%d,%d)  pid: %d\n", 
     *           tmpstring,ival1,0xffff & ntohs(ival1), 0xffff & htons(ival1), ival2);
     */
	if (ival >= 3) {
		int	 replyPortAddr;
		char	*hostname;
		Socket	*pReplySocket;

		replyPortAddr = ival1;
		hostname = &tmpstring[ 0 ];

		pReplySocket = createSocket( SOCK_STREAM );
		if (pReplySocket == NULL)
		  return( -1 );
		ival = openSocket( pReplySocket );
		if (ival != 0)
		  return( -1 );
                /* replyPortAddr is already in network order, 
                 * so switch back so sockets.c can switch back
                 */
		ival = connectSocket( pReplySocket, hostname, 0xFFFF & htons(replyPortAddr) );
		if (ival != 0)
		  return( -2 );

		writeSocket( pReplySocket, message, mlen );
		closeSocket( pReplySocket );
		free( pReplySocket );

		return( 0 );
	}

	tmpMsgQ = openMsgQ( interface );
	if (tmpMsgQ == NULL)
	  return( -1 );

        ival = sendMsgQ( tmpMsgQ, message, mlen, MSGQ_NORMAL, NO_WAIT );

        closeMsgQ( tmpMsgQ );
	return( ival );
}
void ConnectionHandler::startUp()
{
    createSocket();

    QObject::connect(m_socket, SIGNAL(readyRead()), this, SLOT(readyRead()));
    QObject::connect(m_socket, SIGNAL(disconnected()), this, SLOT(disconnected()));
    QObject::connect(m_socket, SIGNAL(error(QAbstractSocket::SocketError)), this, SLOT(error(QAbstractSocket::SocketError)));
}
Пример #23
0
/* After accepting incoming connection connect the client to the server */
void connectToServer(char *ip_address, int port, int *descriptor) {
  struct sockaddr_in address;
  createClientAddrStruct(&address, ip_address, port);
  createSocket(descriptor);
  if (connect(*descriptor, (struct sockaddr *) &address, sizeof(address)) < 0) {
    printErrorMsg("Can't initiate connection on socket\n");
  }
}
Пример #24
0
void clientSend(int count){
  if(sid == -1){
     printf(">>clientSend()~~ ~~sid == -1  \n");
     sid = createSocket();
  }
  char newStr[] ="adam";
  printf(">>clientSend(%d) send() sid is:%d \n",count,sid);
  send(sid,newStr,strlen(newStr)*sizeof(char),0); //no close 
}
Пример #25
0
void TCPClient::socketConnect()
{
    if (m_socket)
        m_socket->close();
    if (m_socket == NULL)
        m_socket = new ClientSocket(this, createSocket());
    log(L_DEBUG, "Start connect %s:%u", getServer(), getPort());
    m_socket->connect(getServer(), getPort(), this);
}
Пример #26
0
Network::Network(int family, int type, std::string proto, size_t len)
{   
  _family = family;
  _id = -1;
  _len = len;
  _change = true;
  _safe = new Mutex();
  createSocket(proto, type);
}
Пример #27
0
int main(){
GtkWidget *play_box1;
GtkWidget *play_box2;
GtkWidget *table;
GtkWidget *label1;
GtkWidget *label2;
gtk_init(0,0);
window1 = gtk_window_new(GTK_WINDOW_TOPLEVEL);
gtk_window_set_position(GTK_WINDOW(window1), GTK_WIN_POS_CENTER);
table = gtk_table_new(100,100, FALSE);
gtk_container_add(GTK_CONTAINER(window1), table);
event_box = gtk_event_box_new ();
fixed = gtk_fixed_new();
gtk_container_add (GTK_CONTAINER (event_box), fixed);

GtkWidget *btn=gtk_button_new_with_label("Dang nhap");
GtkWidget *btn3=gtk_button_new_with_label("Dang ky");
GtkWidget *btn2=gtk_button_new_with_label("Vao choi");

play_box1 = gtk_vbox_new(TRUE, 1);
play_box2 = gtk_vbox_new(TRUE, 1);

//gtk_widget_set_size_request(play_box2,200,200);
//gtk_widget_set_size_request(play_box1,200,200);
label1 = gtk_label_new("Server");
label2 = gtk_label_new("Client");

g_signal_connect(G_OBJECT(btn), "clicked",G_CALLBACK(button_clicked), NULL);
g_signal_connect(G_OBJECT(btn2), "clicked",G_CALLBACK(play), NULL);
g_signal_connect(G_OBJECT(btn3), "clicked",G_CALLBACK(singup_show), NULL);

gtk_box_pack_start(GTK_BOX(play_box1), label1, TRUE, TRUE, 0);
gtk_box_pack_start(GTK_BOX(play_box2), label2, TRUE, TRUE, 0);

gtk_table_attach(GTK_TABLE(table), btn, 0,20,0,30, 
      GTK_FILL | GTK_SHRINK, GTK_FILL | GTK_SHRINK, 5, 5);
gtk_table_attach(GTK_TABLE(table), btn2, 20,40,0,30, 
      GTK_FILL | GTK_SHRINK, GTK_FILL | GTK_SHRINK, 5, 5);
gtk_table_attach(GTK_TABLE(table), btn3, 40,60,0,30, 
      GTK_FILL | GTK_SHRINK, GTK_FILL | GTK_SHRINK, 5, 5);

gtk_table_attach(GTK_TABLE(table), event_box, 0, 70, 30, 100, 
      GTK_FILL | GTK_SHRINK, GTK_FILL | GTK_SHRINK, 5, 5);
gtk_table_attach(GTK_TABLE(table), play_box1, 70, 100, 30,75, 
      GTK_FILL | GTK_SHRINK, GTK_FILL | GTK_SHRINK, 5, 5);
gtk_table_attach(GTK_TABLE(table), play_box2, 70,100, 75,100, 
      GTK_FILL | GTK_SHRINK, GTK_FILL | GTK_SHRINK, 5, 5);

g_signal_connect (G_OBJECT(event_box),"button_press_event", GTK_SIGNAL_FUNC (button_press_callback),fixed);
g_signal_connect(window1, "destroy",G_CALLBACK(exit_play), NULL);

gtk_widget_show_all(window1);
createSocket();
gtk_main();
return 1;
}
Пример #28
0
int main(void) {
    WSADATA Data;
    SOCKADDR_IN recvSockAddr;
    SOCKET recvSocket;
    int status;
    int numrcv = 0;
    struct hostent * remoteHost;
    char * ip;
    const char * host_name = "pb-homework.appspot.com";
    char buffer[MAXBUFLEN];
    char myArray[50];
    memset(buffer,0,MAXBUFLEN);
 // Initialize Windows Socket DLL
    status = WSAStartup(MAKEWORD(2, 2), &Data);
    if(status != 0)
    {
        printf("ERROR: WSAStartup unsuccessful\r\n");
        return 1;
    }
    // Create socket
     recvSocket = createSocket();
	// Get IP address from host name
	remoteHost = gethostbyname(host_name);
	ip = inet_ntoa(*(struct in_addr *)*remoteHost->h_addr_list);
	printf("IP address is: %s.\n", ip);
    memset(&recvSockAddr, 0, sizeof(recvSockAddr)); // zero the sockaddr_in structure
    recvSockAddr.sin_port=htons(PORT); // specify the port portion of the address
    recvSockAddr.sin_family=AF_INET; // specify the address family as Internet
    recvSockAddr.sin_addr.s_addr= inet_addr(ip); // specify ip address



	// Connect

connectToRemoteServer(recvSocket, recvSockAddr);
	// Send request
sendRequest(recvSocket, host_name);
    strcpy(buffer, receiveResponse(recvSocket));
	//Send request with secret param
	sendSecret(recvSocket, host_name, buffer);

    strcpy(buffer, receiveResponse(recvSocket));

    strcpy(myArray, getString(recvSocket, buffer));

    strcpy(myArray, arraySorting(myArray, getArraySize(myArray)));

	//Send POST-request with sorted array
sendPOST(recvSocket, host_name, myArray);
puts(receiveResponse(recvSocket));
	closesocket(recvSocket);
 WSACleanup();
	getchar();
	return EXIT_SUCCESS;

}
Пример #29
0
SocketFd  createSocketAndListen(const char *ip, short port, int backlog/* = 31*/)
{
    SocketFd sockfd = createSocket();
    if(sockfd < 0) return sockfd;

    setNonBlocking(sockfd, true);
    bind(sockfd, ip, port);
    listen(sockfd, backlog);
    return sockfd;
}
Пример #30
0
bool MyMiniClient::runTCP()
{
	SOCKET s = createSocket();
	if(s == INVALID_SOCKET)
	{
		printf("bad socket\n");
		return false;
	}
	sockaddr_in adr = createSendAddr();
	int addr_len = sizeof(adr);
	int connectionResult =  connect(s, (struct sockaddr *)&adr, addr_len);
	if(connectionResult < 0)
	{
		printf("bad connection\n");
		return false;
	}
	else
	{
		printf("good connection\n");
	}

	sockaddr_in incomingAddr;
	//SOCKET s_in =  accept(s, (struct sockaddr *)&incomingAddr, &addr_len);
	int send_size = 0;
	int k = 1;
	char * buffer = new char[256];
	for (int i=1;i<100;i+=2, k+=2)
	{
		if(k >= 10)
		{
			k -=10;
		}
		char* data = new char[2];
		sprintf_s(data,2,"%1d",k);
		send_size = send(s,data,1,0);
		if(send_size > 0)
		{
			printf("->%s\n",data);
		}
		else
		{
			printf("sending error\n");
		}
		if (recv (s,buffer,256,0) < 0)
		{
			printf("receive error\n");
		}
		printf("<-%s\n",buffer);
		Sleep(1000);
		delete data;

	}
	shutdown(s,SD_BOTH);
	closesocket(s);
}