客套話不說了:socket中的send函式可以傳送字串,不能直接傳送結構體,
自己理解:結構體即記憶體中一段連續的記憶體,這樣send中可以傳送結構體指標 上**:
**功能:客戶端傳送給服務端乙個結構體,服務端返回客戶端一字串
客戶端** client.c
#include
#include
#include
#include
#include
#include
#include
#include
#define port
4321
#define buffer_size 1024
typedef struct bat
my;int main(int argc, char *argv)
//位址解析函式
if ((host = gethostbyname(argv[1])) == null)
memset(buf, 0, sizeof(buf));
sprintf(buf, "%s", argv[2]);
//建立socket
if ((sockfd = socket(af_inet, sock_stream, 0)) == -1)
//設定sockaddr_in 結構體相關引數
serv_addr.sin_family = af_inet;
serv_addr.sin_port = htons(port);
serv_addr.sin_addr = *((struct in_addr *)host->h_addr);
bzero(&(serv_addr.sin_zero), 8);
//呼叫connect函式主動發起對伺服器的連線
if(connect(sockfd,(struct sockaddr *)&serv_addr,sizeof(struct sockaddr))== -1)
my buff;
strcpy(buff.group,"bat001");
buff.num=24;
//發訊息給伺服器端
if ((sendbytes = send(sockfd,&buff,sizeof(buff), 0)) == -1)
memset(buf,0,sizeof(buf));
//接收來自伺服器端的返回
if ((recvbytes = recv(sockfd,buf,sizeof(buf), 0)) == -1)
printf("received a message : %s\n",buf);
close(sockfd);
exit(0);
}伺服器端**server.c
#include
#include
#include
#include
#include
#include
#include
#include
#define port
4321
#define buffer_size
1024
#define max_que_conn_nm
5typedef struct bat
my;int main()
printf("socket id = %d\n",sockfd);
//設定sockaddr_in 結構中相關引數
server_sockaddr.sin_family = af_inet;
server_sockaddr.sin_port = htons(port);
server_sockaddr.sin_addr.s_addr = inaddr_any;
bzero(&(server_sockaddr.sin_zero), 8);
int i = 1;//允許重複使用本位址與套接字進行繫結
setsockopt(sockfd, sol_socket, so_reuseaddr, &i, sizeof(i));
//呼叫bind()函式
if (bind(sockfd, (struct sockaddr *)&server_sockaddr,
sizeof(struct sockaddr)) == -1)
printf("bind success!\n");
//呼叫listen()函式,建立未處理請求的佇列
if (listen(sockfd, max_que_conn_nm) == -1)
while(1)
my buff;
//呼叫recv()函式接收客戶端請求
memset(buf , 0, sizeof(buf));
if ((recvbytes = recv(client_fd,&buff,sizeof(buff), 0)) == -1)
printf("received a message: group=%s num=%d\n", buff.group,buff.num);
memset(buf , 0, sizeof(buf));
strcpy(buf,"return to client");
if ((sendbytes = send(client_fd,buf, strlen(buf),0)) == -1)
printf("send message :%s\n",buf);
} close(sockfd);
exit(0);
}gcc client.c -o client
gcc server.c -o server
開兩個終端server終端:./server
socket id = 3
bind success!
listening....
received a message: group=bat001 num=24
send message :return to client
listening....
client終端:./client localhost hello,server
received a message : return to client
socket通訊傳送結構體
socket通訊可以直接傳送結構體!示例 傳送端 c sharp view plain copy struct student struct student student1 接受端 c sharp view plain copy struct student struct student stud...
c c 通過socket傳送結構體
c c 通過socket傳送結構可以直接先將結構轉化到記憶體中,再通過send直接傳送。首先,我們建立乙個結構體。struct usrdata write cfg fd,para,sizeof hd4100 rec t hd4100 rec t是自定義的結構 close cfg fd printf ...
c c 通過socket傳送結構體
c c 通過socket傳送結構體 少游冰雪世界 c c 通過socket傳送結構可以直接先將結構轉化到記憶體中,再通過send直接傳送。首先,我們建立乙個結構體。struct usrdata write cfg fd,para,sizeof hd4100 rec t hd4100 rec t是自定...