TCP 服務端 客戶端 傳輸資料結構

2021-07-14 21:45:54 字數 3244 閱讀 9294

編寫4個檔案 server.c , client.c , sum.h , makefile

主要是客戶端 與服務端在傳輸資料的時候,不是直接傳遞字串,而是傳遞自定義的資料結構

注意:tcp傳送的資訊是以位元組為單位保證順序的.當兩台機器都同時小端機或大端機時,傳輸是正常的。否則,可能會出現異常情況。

server.c

#include 

#include

#include

#include

#include

#include

#include

#include

#include

#include

#include

#include

#include "sum.h"

#define myport 9877

#define queue 20

#define buffer_size 1024

void sig_child(int signo)

/* read n bytes to a descrpiter */

ssize_t readn(int fd,const

void *vptr, size_t n)

nleft -= nread;

ptr += nread;

}return n-nleft;

}/* write n bytes to a descrpiter */

ssize_t writen(int fd,const

void *vptr, size_t n)

nleft = -nwritten;

ptr += nwritten;

}return n;

}void str_echo(int sockfd)

}int main()

// listen,成功返回0,出錯返回-1

if(listen(server_sockfd,queue) == -1)

signal(sigchld, sig_child);// 訊號處理

while(1)

char buff[buffer_size];

// 顯示連線的客戶端

printf("connection from %s, port %d\n",

inet_ntop(af_inet, &client_addr.sin_addr, buff, sizeof(buff)),

ntohs(client_addr.sin_port));

pid_t child_pid ;

if( (child_pid = fork()) == 0 ) // 為客戶端fork子程序

close(conn);

}return

0;}

client.c

#include 

#include

#include

#include

#include

#include

#include

#include

#include

#include

#include "sum.h"

#define myport 9877

#define buffer_size 1024

/* read n bytes to a descrpiter */

ssize_t readn(int fd,const

void *vptr, size_t n)

nleft -= nread;

ptr += nread;

}return n-nleft;

}/* write n bytes to a descrpiter */

ssize_t writen(int fd,const

void *vptr, size_t n)

nleft = -nwritten;

ptr += nwritten;

}return n;

}ssize_t readline(int fd, void *vptr, size_t maxlen)

else

if( rc == 0) else

}*ptr = 0;

return n;

}void str_cli(file *fp, int sockfd)

writen(sockfd, &args, sizeof(args));

if (readn(sockfd, &result, sizeof(result)) == 0)

perror("str_cli: server terminated prematurely");

printf("%ld\n", result.sum);

}}int main()

str_cli(stdin,sock_cli); //回射客戶端的程式

exit(0);

}

sum.h

struct args;

struct result;

makefile

.phony

: build clean

cc=gcc

headers=-i.

debug=-g -ggdb

wall=-wall -w

cflags=$(

wall) $(

debug)

l_cc=$(

cc) $(

cflags) $(

headers)

build:server client

server:server.c

$(l_cc) $< -o $@

client:client.c

$(l_cc) $< -o $@

clean:

@-if [ -f server ]; then rm server; fi

@-if [ -f client ]; then rm client; fi

執行結果如下

TCP客戶端服務端demo

服務端程式 include include include include include include include int main 列印握手成功的客戶端 struct sockaddr in servaddr socklen t nservlen sizeof servaddr getso...

TCP通訊,多客戶端通訊(客戶端 服務端)

客戶端和伺服器間的交流,客戶端傳送資訊,伺服器接收到,並返回資訊 長連線建立socket連線服務端 指定ip位址,埠號 通過ip位址找對應的伺服器 呼叫socket的getinputstream 和getoutputstream 方法獲取和服務端相連的io流 輸入流可以讀取服務端輸出流寫出的資料 輸...

服務端向客戶端傳輸檔案

23.1 閱讀須知 所以如果不符合你的需求就不用往下了。這是用socket傳輸檔案的服務端 include sockaddr in include socket include socket include printf include exit include bzero define serve...