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

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

#include 
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 ;
}


 

你可能感兴趣的:(socket,gtk,平台,dialog,service,button,C,网络)