TCP/IP编程示例
/*
*一个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);
}
}
}