TCP/IP编程示例

TCP/IP编程示例 

http://blog.163.com/yonglin1018@126/blog/getBlog.do?bid=fks_087067087087086066092095080067072087086075093080095064082

/*

*一个socket编程的例子,实现数据的收发。

*作者:雍林

*/

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


 
#define ADD_TO_INT(d ,c ,b , a)   (((unsigned    long)((a) & 0xff) << 24) | ((unsigned    long)((b) & 0xff) << 16) | ((unsigned    long)((c) & 0xff) << 8) | (unsigned    long)((d) & 0xff))

#define TCP_RCV_BUFFER_LEN    1200

void main(void)
{


    SOCKET ServerSocket, CientSocket; //网络连接变量
 struct sockaddr_in LocalAddr, ClientAddr;
    unsigned int msg_len=0;
    char rcv_buffer[TCP_RCV_BUFFER_LEN+1] ;//, szHost[256];;
    unsigned short wite_cnt=0;
    int send_result=0 ;
 int iAddrSize = sizeof(struct sockaddr_in);
 unsigned char close_sock_flag=1;
// HOSTENT* pHost; 
 
 WSADATA wsd;
 WSAStartup( 0x11 , &wsd );

 ServerSocket = socket(AF_INET, SOCK_STREAM, 0);
    if(ServerSocket == INVALID_SOCKET)
 {
    printf("error:%d\n",WSAGetLastError());
    printf("INVALID_SOCKET\n");
 }
 else printf("craet socket ok\n");

 memset(&LocalAddr, 0, sizeof(struct sockaddr_in));
 LocalAddr.sin_family = AF_INET;
 LocalAddr.sin_port = htons(1024); 
 LocalAddr.sin_addr.s_addr = inet_addr("192.168.1.116");
 memset(LocalAddr.sin_zero, 0x00, 8);

/*
 pHost = gethostbyname(szHost);
 if(pHost != NULL)
 {   

  in_addr *addr =(in_addr*) *(pHost->h_addr_list);
  printf("本机信息:%s" , inet_ntoa(addr[0]));

 }
 else printf("get error\n");

*/
 send_result = bind(ServerSocket, (struct sockaddr*)&LocalAddr, sizeof(struct sockaddr_in));

    send_result = listen(ServerSocket, 5);
  
  while (1)
    {
     if(close_sock_flag == 1)//如果socket正确,则保持,不用建立链接
  CientSocket = accept(ServerSocket, (struct sockaddr*)&ClientAddr, &iAddrSize);
     if (CientSocket != -1)
  {
   printf("accept ok\n");
   //读取数据
      msg_len = recv(CientSocket, rcv_buffer, TCP_RCV_BUFFER_LEN , 0);
            if(msg_len > 0)
              {
    //发送数据
                send(CientSocket,rcv_buffer,msg_len,0);
                rcv_buffer[msg_len] = '\0';
       printf("rcvd_ata:%s",rcv_buffer);
                close_sock_flag = 0;
              }
   else close_sock_flag = 1;
  }  
  else close_sock_flag = 1;

  if(close_sock_flag == 1) //若果socket正确,则不用断开链接
  {
   closesocket(CientSocket);
  }

    }

}


评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值