採用UDP協議實現相同功能的程式

2021-09-26 23:53:24 字數 2733 閱讀 5289

客戶端要求:

客戶端可多次向伺服器傳送資料;

客戶端能夠接收伺服器端傳送資料,並回顯正確;

伺服器端要求:

執行埠可配置

將客戶端傳送來的訊息正確顯示,並將該訊息傳送給客戶端;

支援多個客戶端同時傳送

tcp套接字程式設計

udp套接字程式設計

udpserver.c

#include

#include

#include

#include

#include

#include

#include

#include

void

print_usage

(char

* cmd)

intmain

(int argc,

char

** ar**)

port =

atoi

(ar**[1]

);memset

(send_buf,0,

2048);

//將send_buf置為0

memset

(recv_buf,0,

2048);

sockfd=

socket

(af_inet,sock_dgram,0)

;// ipv4協議,資料報套介面if(

-1==sockfd)

#ifdef debug

printf

("the listen id is %d\n"

,sockfd)

;#endif

memset

(&server,0,

sizeof

(struct sockaddr_in));

server.sin_family = af_inet;

server.sin_addr.s_addr =

htonl

(inaddr_any)

; server.sin_port =

htons

(port)

;//埠號,需要網路序轉換

ret =

bind

(sockfd,

(struct sockaddr*

)&server,

sizeof

(server));

//繫結埠

if(ret <0)

while(1

)printf

("client:%s\n"

,recv_buf)

;//列印client發過來的資訊

sendto

(sockfd, recv_buf,

sizeof

(send_buf),0

,(struct sockaddr*

)&client, len)

;//傳送資訊給client

}close

(sockfd)

;return0;

}

udpclient.c

#include

#include

#include

#include

#include

#include

#include

#include

void

print_usage

(char

* cmd)

intmain

(int argc,

char

** ar**)

if(argc !=3)

port =

atoi

(ar**[2]

);memset

(&ser_addr,0,

sizeof

(ser_addr));

ser_addr.sin_family = af_inet;

ser_addr.sin_addr.s_addr =

inet_addr

(ar**[1]

);ser_addr.sin_port =

htons

(port)

;//注意網路序轉換

len =

sizeof

(ser_addr)

;printf

("what words do you want to tell to server?\n");

while(1

)close

(sockfd)

;return0;

}

1、 編譯源**

gcc udpserver.c -o udpserver

gcc udpclient.c -o udpclient

2、 更換到root使用者,並執行udpserver,指定埠為8080

3、 在新視窗執行客戶端,指定ip為192.168.42.40,埠為8080,

傳送訊息 first ,服務端接收到訊息後返回同樣的內容給客戶端

4、 再開啟乙個視窗,執行客戶端,指定ip為127.0.0.1,埠為8080,

傳送訊息 second,服務端接收到訊息後返回同樣的內容給相應的客戶端

5、 在第乙個客戶端向服務端傳送訊息 third ,服務端返回相應內容

採用UDP協議實現客戶端與服務端的通訊

實驗要求 實驗環境 red hat 9 udpclient.c include include include include include include include include define port 8900 void print usage char cmd intmain int...

UDP實現簡單的ifconfig查詢功能

一 include for ifconf include for net status mask include for sockaddr in include include include include include for close include include define max ...

udp實現簡單的多人聊天功能

多個客戶端向伺服器傳送資訊,服務端再將資訊返回到各個客戶端。這是接收udp的實現類 public class rec implements runnable override public void run catch ioexception e 獲得訊息 string info new strin...