我是
靠谱客的博主
无限小笼包,最近开发中收集的这篇文章主要介绍
TCP/IP协议实现客服端与服务器的双向发送,觉得挺不错的,现在分享给大家,希望可以做个参考。
概述
1、服务器程序
#include <sys/types.h>
/* See NOTES */
#include <sys/socket.h>
#include <string.h>
#include <sys/socket.h>
#include <netinet/in.h>
#include <arpa/inet.h>
#include <unistd.h>
#include <stdio.h>
#include <signal.h>
/*
* socket
* bind
* listen
* accept
* send/recv
*/
#define SERVER_PORT 8888
#define BACKLOG
10
/* ./server ip */
int main(int argc, char **argv)
{
int iRet;
int iRecvLen;
int iSendLen;
int iSocketServer;
int iSocketClient;
int iAddrLen;
unsigned char ucRecvByte[1000];
unsigned char ucSendByte[1000];
struct sockaddr_in tSocketServerAddr;
struct sockaddr_in tSocketClientAddr;
int iClientNum = -1;
signal(SIGCHLD,SIG_IGN);
iSocketServer = socket(AF_INET, SOCK_STREAM, 0);
tSocketServerAddr.sin_family = AF_INET;
tSocketServerAddr.sin_port
= htons(SERVER_PORT);
tSocketServerAddr.sin_addr.s_addr = INADDR_ANY;
memset(tSocketServerAddr.sin_zero, 0, 8);
iRet = bind(iSocketServer, (const struct sockaddr *)&tSocketServerAddr, sizeof(struct sockaddr));
if(iRet == -1)
{
printf("server bind errorn");
return -1;
}
iRet = listen(iSocketServer, BACKLOG);
if (-1 == iRet)
{
printf("listen error!n");
return -1;
}
while(1)
{
iAddrLen = sizeof(struct sockaddr);
iSocketClient = accept(iSocketServer, (struct sockaddr *)&tSocketClientAddr, &iAddrLen);
if(iSocketClient != -1)
{
iClientNum++;
printf("Get connect from client %d : %sn",
iClientNum, inet_ntoa(tSocketClientAddr.sin_addr));
if(fork() == 0)
{
while(1)
{
iRecvLen = recv(iSocketClient, ucRecvByte, 999, 0);
if(iRecvLen <= 0)
{
close(iSocketClient);
return -1;
}
else
{
ucRecvByte[iRecvLen] = '