window平台下gtk+socket简单学习。

1.使用dev-c++作为IDE时,需在”编译器项“中的“添加命令行编辑框“中添加socket的lib库-lwsock32
2.使用glade 添加一个按钮,并添加clicked的信号会自动生成此信号的回调函数
3.在此回调函数实现创建socket/绑定端口/监听套接字,发现有客户端连接就弹出一个对话框提示,然后关闭连接;具体代码如下:
 

#include <winsock2.h>
void
on_button1_clicked                     (GtkButton       *button,
                                        gpointer         user_data)
{
  //----------------------
  // Initialize Winsock.
  WSADATA wsaData;
  SOCKET ListenSocket,AcceptSocket;
  int iResult;
  struct sockaddr_in service;
  

  iResult = WSAStartup(MAKEWORD(2,2), &wsaData);
  if (iResult != NO_ERROR) {
    printf("Error at WSAStartup()\n");
    return ;
  }
 
  //----------------------
  // Create a SOCKET for listening for
  // incoming connection requests.
  
  ListenSocket = socket(AF_INET, SOCK_STREAM, IPPROTO_TCP);
  if (ListenSocket == INVALID_SOCKET) {
    printf("Error at socket(): %ld\n", WSAGetLastError());
    WSACleanup();
    return ;
  }
 
  //----------------------
  // The sockaddr_in structure specifies the address family,
  // IP address, and port for the socket that is being bound.
  
  service.sin_family = AF_INET;
  service.sin_addr.s_addr = inet_addr("127.0.0.1");
  service.sin_port = htons(27015);

  if (bind( ListenSocket, 
    (SOCKADDR*) &service, 
    sizeof(service)) == SOCKET_ERROR) {
    printf("bind() failed.\n");
    closesocket(ListenSocket);
    WSACleanup();
    return ;
  }

  //----------------------
  // Listen for incoming connection requests.
  // on the created socket
  if (listen( ListenSocket, 1 ) == SOCKET_ERROR) {
    printf("Error listening on socket.\n");
    closesocket(ListenSocket);
    WSACleanup();
    return ;
  }

  //----------------------
  // Create a SOCKET for accepting incoming requests.
  printf("Waiting for client to connect...\n");

  //----------------------
  // Accept the connection.
  AcceptSocket = accept( ListenSocket, NULL, NULL );
  if (AcceptSocket == INVALID_SOCKET) {
    printf("accept failed: %d\n", WSAGetLastError());
    closesocket(ListenSocket);
    WSACleanup();
    return ;
  } else
  {
    printf("Client connected.\n");
    GtkWidget *dialog;
 dialog = gtk_message_dialog_new (NULL,0, GTK_MESSAGE_INFO,GTK_BUTTONS_OK,"lient connected");
 gtk_dialog_run(GTK_DIALOG(dialog));//显示并运行对话框
 gtk_widget_destroy(dialog);//销毁对话框
  }
  
  // No longer need server socket
  closesocket(ListenSocket);

  WSACleanup();
  return ;
}


 

阅读更多
个人分类: 网络 C
想对作者说点什么? 我来说一句

dos 命令详解

2018年01月06日 77.43MB 下载

WINSHELL5 源码

2008年06月12日 23KB 下载

mongodb安装与配置

2014年09月14日 63KB 下载

windows系统下破解密码教程

2013年06月17日 1.37MB 下载

没有更多推荐了,返回首页

加入CSDN,享受更精准的内容推荐,与500万程序员共同成长!
关闭
关闭