在vc中怎么使用socket呀
告诉我一下需要用的头文件,以及需要调用得初始化函数等,最好给我一个小例子,关于用udp发数据的
谢谢大家,我不用vc好多年了,告诉我代码都要放到什么地方,在感谢一次
分我只能给100了

解决方案 »

  1.   

    服务端:
    1.初始化socket环境,创建socket
    2.梆定一个端口
    3.开始监听
    4.接收客户端
    5.接收到客户端之后,使用这个socket来与这个客户通信#include "stdAfx.h"
    #include <winsock2.h>
    #include <mswsock.h>
    #include <iostream>using namespace std;#pragma comment(lib, "ws2_32.lib")
    #pragma comment(lib, "mswsock.lib")DWORD IniSOCKDLL()
    {
     WORD wVersionRequested;
     WSADATA wsaData;
     int err=0;
     
     wVersionRequested = MAKEWORD( 2, 2 );
     err = WSAStartup( wVersionRequested, &wsaData ); 
     return err;
    }int main(int argc, char* argv[])
    {
     cout<<"程序开始"<<endl;
     IniSOCKDLL();
     SOCKET ss=WSASocket(AF_INET,
      SOCK_STREAM,
      0,
      NULL,
      0,
      NULL);
     
     SOCKADDR_IN addr;
     int len;
     addr.sin_family=AF_INET;
     addr.sin_addr.s_addr = htonl(INADDR_ANY);
     addr.sin_port = htons(1002);
     len=sizeof(addr);
     
     bind(ss , (PSOCKADDR)&addr , len);
     listen(ss,5);
     
     SOCKET sc=accept(ss,(PSOCKADDR)&addr,&len);
     char buff[1024];
     ZeroMemory(buff,1024);
     recv(sc,buff,1024,0);
     cout<<buff<<endl;
     
     ZeroMemory(buff,1024);
     memcpy(buff,"123",3);
     send(sc,buff,3,0);
     
     closesocket(sc);
     closesocket(ss);
     return 0;
    }客户端:
    1.初始化socket环境,创建socket
    2.连接服务端
    3.开启一个线程来接收数据
    4.使用send直接发数据包#include "stdAfx.h"
    #include <winsock2.h>
    #include <mswsock.h>
    #include <iostream>using namespace std;#pragma comment(lib, "ws2_32.lib")
    #pragma comment(lib, "mswsock.lib")DWORD IniSOCKDLL()
    {
     WORD wVersionRequested;
     WSADATA wsaData;
     int err=0;
     
     wVersionRequested = MAKEWORD( 2, 2 );
     err = WSAStartup( wVersionRequested, &wsaData ); 
     return err;
    }int main(int argc, char* argv[])
    {
     IniSOCKDLL();
     SOCKET sc=WSASocket(AF_INET,
      SOCK_STREAM,
      0,
      NULL,
      0,
      NULL);
     
     SOCKADDR_IN addr;
     int len;
     addr.sin_family=AF_INET;
     addr.sin_addr.s_addr = inet_addr("127.0.0.1");
     addr.sin_port = htons(1002);
     len=sizeof(addr);
     
     connect(sc, (struct sockaddr *)&addr, len);
     
     char buff[1024];
     ZeroMemory(buff,1024);
     memcpy(buff,"123",3);
     send(sc,buff,3,0); recv(sc,buff,1024,0);
     cout<<buff<<endl; closesocket(sc);
     return 0;
    }
      

  2.   

    谢谢你
    对不起 ,我问一下,你这各代码是vc++ 6.0 吗,我要在vc6下实现
      

  3.   

    例子代码有很多
    http://www.vckbase.com/document/listdoc.asp?mclsid=9&sclsid=901
      

  4.   

    这个是在6.0下写的啊。
    你用那个控制台工程。
    加入一个CPP文件。
    把代码帖好就行了。
      

  5.   

    给你一个更简单的:
    // Module Name: tcpclient.cpp
    //
    // Description:
    //
    //    This sample illustrates how to develop a simple TCP client application
    //    that can send a simple "hello" message to a TCP server listening on port 5150.
    //    This sample is implemented as a console-style application and simply prints
    //    status messages a connection is made and when data is sent to the server.
    //
    // Compile:
    //
    //    cl -o tcpclient tcpclient.cpp ws2_32.lib
    //
    // Command Line Options:
    //
    //    tcpclient.exe <server IP address> 
    //#include <winsock2.h>
    #include <stdio.h>void main(int argc, char **argv)
    {
       WSADATA              wsaData;
       SOCKET               s;
       SOCKADDR_IN          ServerAddr;
       int                  Port = 5150;
       int                  Ret;   if (argc <= 1)
       {
          printf("USAGE: tcpclient <Server IP address>.\n");
          return;
       }   // Initialize Winsock version 2.2   if ((Ret = WSAStartup(MAKEWORD(2,2), &wsaData)) != 0)
       {
          // NOTE: Since Winsock failed to load we cannot use WSAGetLastError 
          // to determine the error code as is normally done when a Winsock 
          // API fails. We have to report the return status of the function.      printf("WSAStartup failed with error %d\n", Ret);
          return;
       }
       
       // Create a new socket to make a client connection.
     
       if ((s = socket(AF_INET, SOCK_STREAM, IPPROTO_TCP))
           == INVALID_SOCKET)
       {
          printf("socket failed with error %d\n", WSAGetLastError());
          WSACleanup();
          return;
       }
     
       // Setup a SOCKADDR_IN structure that will be used to connect
       // to a listening server on port 5150. For demonstration
       // purposes, we required the user to supply an IP address
       // on the command line and we filled this field in with the 
       // data from the user.   ServerAddr.sin_family = AF_INET;
       ServerAddr.sin_port = htons(Port);    
       ServerAddr.sin_addr.s_addr = inet_addr(argv[1]);   // Make a connection to the server with socket s.   printf("We are trying to connect to %s:%d...\n",
              inet_ntoa(ServerAddr.sin_addr), htons(ServerAddr.sin_port));   if (connect(s, (SOCKADDR *) &ServerAddr, sizeof(ServerAddr)) 
           == SOCKET_ERROR)
       {
          printf("connect failed with error %d\n", WSAGetLastError());
          closesocket(s);
          WSACleanup();
          return;
       }    printf("Our connection succeeded.\n");
          
       // At this point you can start sending or receiving data on
       // the socket s. We will just send a hello message to the server.   printf("We will now try to send a hello message.\n");   if ((Ret = send(s, "Hello", 5, 0)) == SOCKET_ERROR)
       {
          printf("send failed with error %d\n", WSAGetLastError());
          closesocket(s);
          WSACleanup();
          return;
       }   printf("We successfully sent %d byte(s).\n", Ret);   // When you are finished sending and receiving data on socket s,
       // you should close the socket.   printf("We are closing the connection.\n");   closesocket(s);   // When your application is finished handling the connection, call
       // WSACleanup.   WSACleanup();
    }
    ××××××××××××××××××××××××××××××××××××××××××××××
    // Module Name: tcpclient.cpp
    //
    // Description:
    //
    //    This sample illustrates how to develop a simple TCP client application
    //    that can send a simple "hello" message to a TCP server listening on port 5150.
    //    This sample is implemented as a console-style application and simply prints
    //    status messages a connection is made and when data is sent to the server.
    //
    // Compile:
    //
    //    cl -o tcpclient tcpclient.cpp ws2_32.lib
    //
    // Command Line Options:
    //
    //    tcpclient.exe <server IP address> 
    //#include <winsock2.h>
    #include <stdio.h>void main(int argc, char **argv)
    {
       WSADATA              wsaData;
       SOCKET               s;
       SOCKADDR_IN          ServerAddr;
       int                  Port = 5150;
       int                  Ret;   if (argc <= 1)
       {
          printf("USAGE: tcpclient <Server IP address>.\n");
          return;
       }   // Initialize Winsock version 2.2   if ((Ret = WSAStartup(MAKEWORD(2,2), &wsaData)) != 0)
       {
          // NOTE: Since Winsock failed to load we cannot use WSAGetLastError 
          // to determine the error code as is normally done when a Winsock 
          // API fails. We have to report the return status of the function.      printf("WSAStartup failed with error %d\n", Ret);
          return;
       }
       
       // Create a new socket to make a client connection.
     
       if ((s = socket(AF_INET, SOCK_STREAM, IPPROTO_TCP))
           == INVALID_SOCKET)
       {
          printf("socket failed with error %d\n", WSAGetLastError());
          WSACleanup();
          return;
       }
     
       // Setup a SOCKADDR_IN structure that will be used to connect
       // to a listening server on port 5150. For demonstration
       // purposes, we required the user to supply an IP address
       // on the command line and we filled this field in with the 
       // data from the user.   ServerAddr.sin_family = AF_INET;
       ServerAddr.sin_port = htons(Port);    
       ServerAddr.sin_addr.s_addr = inet_addr(argv[1]);   // Make a connection to the server with socket s.   printf("We are trying to connect to %s:%d...\n",
              inet_ntoa(ServerAddr.sin_addr), htons(ServerAddr.sin_port));   if (connect(s, (SOCKADDR *) &ServerAddr, sizeof(ServerAddr)) 
           == SOCKET_ERROR)
       {
          printf("connect failed with error %d\n", WSAGetLastError());
          closesocket(s);
          WSACleanup();
          return;
       }    printf("Our connection succeeded.\n");
          
       // At this point you can start sending or receiving data on
       // the socket s. We will just send a hello message to the server.   printf("We will now try to send a hello message.\n");   if ((Ret = send(s, "Hello", 5, 0)) == SOCKET_ERROR)
       {
          printf("send failed with error %d\n", WSAGetLastError());
          closesocket(s);
          WSACleanup();
          return;
       }   printf("We successfully sent %d byte(s).\n", Ret);   // When you are finished sending and receiving data on socket s,
       // you should close the socket.   printf("We are closing the connection.\n");   closesocket(s);   // When your application is finished handling the connection, call
       // WSACleanup.   WSACleanup();
    }
      

  6.   

    这个是UDP的:
    // Module Name: udpreceiver.cpp
    //
    // Description:
    //
    //    This sample illustrates how to develop a simple UDP receiver application
    //    that awaits datagrams on port 5150. This sample is implemented as a 
    //    console-style application and simply prints status messages when data is
    //    received.
    //
    // Compile:
    //
    //    cl -o udpreceiver udpreceiver.cpp ws2_32.lib
    //
    // Command Line Options:
    //
    //    udpreceiver.exe
    //
    //    NOTE: There are no command parameters. 
    //
    #include <winsock2.h>
    #include <stdio.h>void main(void)
    {
       WSADATA              wsaData;
       SOCKET               ReceivingSocket;
       SOCKADDR_IN          ReceiverAddr;
       int                  Port = 5150;
       char                 ReceiveBuf[1024];
       int                  BufLength = 1024;
       SOCKADDR_IN          SenderAddr;
       int                  SenderAddrSize = sizeof(SenderAddr);
       int                  Ret;
       // Initialize Winsock version 2.2   if ((Ret = WSAStartup(MAKEWORD(2,2), &wsaData)) != 0)
       {
          // NOTE: Since Winsock failed to load we cannot use WSAGetLastError 
          // to determine the error code as is normally done when a Winsock 
          // API fails. We have to report the return status of the function.      printf("ERROR: WSAStartup failed with error %d\n", Ret);
          return;
       }   
       // Create a new socket to receive datagrams on.
     
       if ((ReceivingSocket = socket(AF_INET, SOCK_DGRAM, IPPROTO_UDP))
           == INVALID_SOCKET)
       {
          printf("ERROR: socket failed with error %d\n", WSAGetLastError());
          WSACleanup();
          return;
       }    // Setup a SOCKADDR_IN structure that will tell bind that we
       // want to receive datagrams from all interfaces using port
       // 5150.   ReceiverAddr.sin_family = AF_INET;
       ReceiverAddr.sin_port = htons(Port);    
       ReceiverAddr.sin_addr.s_addr = htonl(INADDR_ANY);   // Associate the address information with the socket using bind.   if (bind(ReceivingSocket, (SOCKADDR *)&ReceiverAddr, sizeof(ReceiverAddr))
           == SOCKET_ERROR)
       {
          printf("ERROR: bind failed with error %d\n", WSAGetLastError());
          closesocket(ReceivingSocket);
          WSACleanup();
          return;
       }   printf("We are ready to receive 1 datagram from any interface on port %d...\n",
              Port);   // At this point you can receive datagrams on your bound socket.   if ((Ret = recvfrom(ReceivingSocket, ReceiveBuf, BufLength, 0,
           (SOCKADDR *)&SenderAddr, &SenderAddrSize)) == SOCKET_ERROR)
       {
          printf("ERROR: recvfrom failed with error %d\n", WSAGetLastError());
          closesocket(ReceivingSocket);
          WSACleanup();
          return;
       }   printf("We successfully received %d bytes from address %s:%d.\n", Ret,
              inet_ntoa(SenderAddr.sin_addr), ntohs(SenderAddr.sin_port));
       // When your application is finished receiving datagrams close
       // the socket.   closesocket(ReceivingSocket);   // When your application is finished call WSACleanup.   WSACleanup();
    }××××××××××××××××××××××××××××××××××××××××
    // Module Name: udpsender.cpp
    //
    // Description:
    //
    //    This sample illustrates how to develop a simple UDP sender application
    //    that can send a simple "hello" message to a UDP receiver awaiting datagrams
    //    on port 5150. This sample is implemented as a console-style application and 
    //    simply prints status messages as data is sent to the server.
    //
    // Compile:
    //
    //    cl -o udpsender udpsender.cpp ws2_32.lib
    //
    // Command Line Options:
    //
    //    udpsender.exe <receiver IP address> 
    //
    #include <winsock2.h>
    #include <stdio.h>void main(int argc, char **argv)
    {
       WSADATA              wsaData;
       SOCKET               SendingSocket;
       SOCKADDR_IN          ReceiverAddr;
       int                  Port = 5150;
       int                  Ret;   if (argc <= 1)
       {
          printf("USAGE: udpsender <receiver IP address>.\n");
          return;
       }   // Initialize Winsock version 2.2   if ((Ret = WSAStartup(MAKEWORD(2,2), &wsaData)) != 0)
       {
          // NOTE: Since Winsock failed to load we cannot use WSAGetLastError 
          // to determine the error code as is normally done when a Winsock 
          // API fails. We have to report the return status of the function.      printf("ERROR: WSAStartup failed with error %d\n", Ret);
          return;
       }
       
       // Create a new socket to receive datagrams on.
     
       if ((SendingSocket = socket(AF_INET, SOCK_DGRAM, IPPROTO_UDP))
           == INVALID_SOCKET)
       {
          printf("ERROR: socket failed with error %d\n", WSAGetLastError());
          WSACleanup();
          return;
       }   // Setup a SOCKADDR_IN structure that will identify who we
       // will send datagrams to. For demonstration purposes, let's
       // assume our receiver's IP address is 136.149.3.29 and waits
       // for datagrams on port 5150. Obviously you will want to prompt 
       // the user for an IP address and port number and fill these 
       // fields in with the data from the user.   ReceiverAddr.sin_family = AF_INET;
       ReceiverAddr.sin_port = htons(Port);    
       ReceiverAddr.sin_addr.s_addr = inet_addr(argv[1]);   // Send a datagram to the receiver.   if ((Ret = sendto(SendingSocket, "Hello", 5, 0, 
           (SOCKADDR *)&ReceiverAddr, sizeof(ReceiverAddr))) == SOCKET_ERROR)
       {
          printf("ERROR: sendto failed with error %d\n", WSAGetLastError());
          closesocket(SendingSocket);
          WSACleanup();
          return;
       }   // When your application is finished sending datagrams close
       // the socket.   printf("We successfully sent %d byte(s) to %s:%d.\n", Ret,
              inet_ntoa(ReceiverAddr.sin_addr), htons(ReceiverAddr.sin_port));   closesocket(SendingSocket);   // When your application is finished call WSACleanup.   WSACleanup();
    }