udpsocket 通訊C 例子

2022-08-01 00:45:10 字數 2903 閱讀 9268

服務端**:

using

system;

using

system.collections.generic;

using

system.linq;

using

system.net;

using

system.net.sockets;

using

system.text;

using

system.threading.tasks;

namespace

udpsocketserver

", dns.gethostname());

console.writeline(

"等待客戶端連線.....");

ipendpoint sender = new ipendpoint(ipaddress.any, 0

); endpoint remote =(endpoint)(sender);

recv = newsock.receivefrom(revdata, ref

remote);

console.writeline(

"我是服務端,客戶端連線成功

", remote.tostring());

console.writeline(encoding.unicode.getstring(revdata,

0, recv));

string welcome = "

你好,我是伺服器";

senddata =encoding.unicode.getbytes(welcome);

newsock.sendto(senddata, senddata.length, socketflags.none, remote);

while (true

) 傳送:

", remote.tostring(), encoding.unicode.getstring(senddata, 0

, recv));

console.writeline(recvdata);

//string recvdata =string.format("伺服器接收到資料", encoding.ascii.getstring(data, 0, recv));

string recvdatesucceed = string.format("

伺服器已收到.");

senddata =encoding.unicode.getbytes(recvdatesucceed);

newsock.sendto(senddata, senddata.length, socketflags.none, remote);}}

}}

客戶端**:

using

system;

using

system.collections.generic;

using

system.linq;

using

system.net;

using

system.net.sockets;

using

system.text;

using

system.threading.tasks;

namespace

udpsocketdemo

", dns.gethostname());

//設定服務ip,設定tcp埠號

ipendpoint ip = new ipendpoint(ipaddress.parse("

127.0.0.1

"), 6666

);

//定義網路型別,資料連線型別和網路協議udp

socket server = new

socket(addressfamily.internetwork, sockettype.dgram, protocoltype.udp);

string welcome = "

你好伺服器,我是客戶端! ";

data =encoding.unicode.getbytes(welcome);

server.sendto(data, data.length, socketflags.none, ip);

ipendpoint sender = new ipendpoint(ipaddress.any, 0

); endpoint remote =(endpoint)sender;

byte senddata = new

byte[1024

];

//對於不存在的ip位址,加入此行**後,可以在指定時間內解除阻塞模式限制

int recv = server.receivefrom(senddata, ref

remote);

console.writeline(

"我是客戶端,從伺服器端: 接收到訊息

", remote.tostring());

console.writeline(encoding.unicode.getstring(senddata,

0, recv));

while (true

) 傳送:

", remote.tostring(), encoding.unicode.getstring(recvdata, 0

, recv));

console.writeline(stringdata);

}console.writeline(

"服務停止.");

server.close();}}

}

說明: 客戶端直接傳送內容,伺服器端直接接收

基於C 的UDP socket 通訊

udp是面向無連線的,盡最大努力交付的不可靠通訊協議。相比tcp,少了握手建立連線,維護連線,連線釋放等一系列過程,因此具有很小的資源消耗和處理速度快的點。可實現一對一,一對多,多對一,多地多的udp client通訊。不同於tcp,udp應用上已經無嚴格意義上的真正的伺服器和客戶端之分了,端點之間...

C 簡單的UDP通訊例子

1 1,udp客戶端23 using system 4using system.collections.generic 5using system.componentmodel 6using system.data 7using system.drawing 8using system.linq 9...

C udp 通訊 例子

upd通訊接受端 using system using system.collections.generic using system.text using system.net using system.net.sockets namespace zhty.socket.udpsocket pub...