依睛(IT blog) 我回来了,PHP<-->C/C++ LINUX

笨鸟

统计

积分与排名

友情连接

最新评论

socket 编程

/*****************************
//文件名server.cpp
socket 服务端程序
*****************************/

#include <iostream>
#include <winsock2.h>

#pragma comment(lib, "ws2_32")
#define LEN  1024
using namespace std;
int main()
{
 int    err;
 char   buf[LEN];
 SOCKET   s;
 SOCKET   sClient; 
 WORD wdVersionRequired;  
 WSADATA wsaData;

 wdVersionRequired = MAKEWORD(2, 2);    //³ÌÐòҪʹÓÃ2.2°æ±¾
 err = WSAStartup(wdVersionRequired, &wsaData); // ³õʼ»¯WinSock¿â¡£
 //×¢Ò⺯Êý·µ»ØÖµ£¬0±íʾÕý³£

 if (0 != err)
 {
  return -1;
 }
 s = socket(AF_INET, SOCK_STREAM, 0); //socket()´´½¨

 if (-1 == s)
 {
  cout <<" create socket error"<< endl;
  return -1;
 }
 sockaddr_in saServer;
 saServer.sin_family = AF_INET;
 saServer.sin_addr.S_un.S_addr = inet_addr("192.168.2.80");
 saServer.sin_port = htons(8066);

 err = bind(s, (const sockaddr *)&saServer, sizeof(sockaddr)); //bind()
 if (0 != err)
 {
  cout <<"failed bind"<< endl;
  return -1;
 }

 err = listen(s, 10); //listen()¼àÌý
 if (0 != err)
 {
  cout <<"failed listen"<< endl;
  return -1;
 }

 sockaddr sa;

 int salen = sizeof(sockaddr);
 sClient = accept(s, &sa, &salen);
 while(1)
 { 
        memset(buf, 0, sizeof(buf));
  err = recv(sClient, buf, sizeof(buf), 0);
  send(sClient, buf, sizeof(buf), 0);
  cout <<buf<< endl;
 } 

 WSACleanup();
 closesocket(s);
 closesocket(sClient);
 return 1;
}

==============================================

/*****************************
//文件名client.cpp
socket 客户端程序
*****************************/

#include <windows.h>
#include <iostream>
#pragma comment(lib, "ws2_32")

using namespace std;
#define LEN  1024
int main()
{
 int  i=0;
 char buf1[LEN];
 char buf[LEN];
 WORD wdVersionRequired;
 WSADATA wsaData;
   
 wdVersionRequired = MAKEWORD(2, 2);  /* 2.2°汾 */
 WSAStartup(wdVersionRequired, &wsaData);

 SOCKET s = socket(AF_INET, SOCK_STREAM, 0);
 if (SOCKET_ERROR == s)
 {
  return 0;
 }

 sockaddr_in    saServer;
 memset(&saServer, 0, sizeof(saServer));
 saServer.sin_family = AF_INET;
 saServer.sin_addr.S_un.S_addr = inet_addr("192.168.2.80");
 saServer.sin_port = htons(8066);

 if(connect(s, (const sockaddr*)&saServer, sizeof(sockaddr)) != 0)
 {
  perror("error");
  exit(-1);
 }

 while(1)
 {
  gets(buf);
  if(0 == send(s, buf, sizeof(buf), 0))  //send server
  {
   perror("error");
   break;
  }
  recv(s, buf1, sizeof(buf1), 0);
  printf("buf1: %s\n", buf1);
  printf("send success!\n");
 }

 WSACleanup();
 closesocket(s);

 return 1;
}




本程序可以运行, 如果不可以将要提出问题.

posted on 2008-11-24 12:17 向左向右走 阅读(143) 评论(0)  编辑 收藏 引用

只有注册用户登录后才能发表评论。