Linux Socket程式設計簡單例項

2021-08-25 15:00:28 字數 1808 閱讀 8872

#include#include#include#include#include#include#includechar *host_name="127.0.0.1";

int port=7778;

struct student

t=;int main ( )

if(connect(socket_descriptor,(void *)&pin,sizeof (pin))==-1)

printf("send message to server .../n");

//memset(buf,0,502);

//memcpy(buf,(void *)&t,sizeof(t));

//sprintf(buf,"%s %d",t.name,t.num);

//printf("the first string : %s/n",buf);

if(send(socket_descriptor,(void *) &t,sizeof(t),0)==-1)

printf("waiting for response from server!/n");

memset(buf,0,502);

if(recv(socket_descriptor,buf,sizeof(buf),0)==-1)

printf("/n response from server : /n");

memcpy((struct student *)&t,buf,sizeof(buf));

//printf("the string : %s /n",rebuf);

printf("--%s--%s--%5.1f--/n",t.name,t.num,t.score);

close (socket_descriptor);

} /* 注意在send 結構體時應該把結構體強制型別轉換為void * 型

** 接受之後又要強制轉換回結構體型!否則則穿過來的是結構體的

** 一部分!

*/下面是服務端

#include#include#include#include#include#includeint port=7778;

struct student

t;main()

bzero(&sin,sizeof(sin));

sin.sin_addr.s_addr=inaddr_any;

sin.sin_port=htons(port);

if(bind(sock_descriptor,(struct sockaddr *)&sin,sizeof (sin))==-1)

if(listen (sock_descriptor,20)==-1)

printf("waiting for accepting connection from client!/n");

while(1)

memset(buf,0,502);

if(recv(temp_sock_descriptor,buf,sizeof(buf),0)==-1)

printf("received : /n");

//printf("the recv buf is :%s/n",buf);

memcpy((struct student *) &t,buf,sizeof(buf));

printf("--%s--%s--%5.1f--/n",t.name,t.num,t.score);

if(send (temp_sock_descriptor,(void *) &t,sizeof(t),0)==-1)

close (temp_sock_descriptor);

}}

linux socket簡單程式設計入門

開發環境vs2019 加 ubuntu虛擬機器 環境搭配參考相關部落格 伺服器端,有socket,bind,listen,accept,write,close 六個函式 客戶端有socket,connect,write,close四個函式 伺服器端 include include include i...

linux socket 程式設計

兩段程式 可用於開發板和主機之間的資料傳輸,很管用!file client.c檔案傳輸客戶端程式示例 本檔案是客戶機的 include for sockaddr in include for socket include for socket include for printf include f...

linux socket程式設計

雙休日無聊透頂,看了四五集 反恐24小時 實在不想看了,於是就想搞linux的socket programming來玩玩,前期資料都準備好 早就想寫個看看了。首先,寫個簡單的client端的程式 呵,其實是copy!server端用的是網上當的乙個除錯工具 一開始用的是以前用過的乙個多執行緒執行的介...