C 中Socket通訊用法UDP方式和TCP方式

2021-10-04 10:34:06 字數 2487 閱讀 2490

using system.net.sockets;

using system.net;

一、udp方式:

伺服器端**:

static

void

main

(string

args)

:", remote.

tostring()

);console.

writeline

(encoding.ascii.

getstring

(data,

0, recv));

string welcome =

"welcome to my test server!"

; data = encoding.ascii.

getbytes

(welcome)

; newsock.

sendto

(data, data.length, socketflags.none, remote)

;while

(true

)}

客戶端**:

```csharp

void

maininfo()

:", remote.

tostring()

);console.

writeline

(encoding.ascii.

getstring

(data,

0, recv));

while

(true

)//讀取資料

server.

sendto

(encoding.ascii.

getbytes

(input)

, remote)

;//將資料傳送到指定的終結點remote

data =

newbyte

[1024];

recv = server.

receivefrom

(data,

ref remote)

;//從remote接受資料

stringdata = encoding.ascii.

getstring

(data,

0, recv)

; console.

writeline

(stringdata);}

console.

writeline

("stopping client");

server.

close()

;}

二、tcp方式:

伺服器端**:

socket serversocket =

null

;thread clientthread =

null

;socket clientsocket =

null

;thread thread =

null

;ipaddress ips =

null

;pendpoint ipep =

null

;void

serverstart()

catch

(exception ex)}}

static

void

receivedata

(object obj)

content +

= system.text.encoding.unicode.

getstring

(buffer,

0, buflen);}

catch

(exception ex)

}send

(s, content)

; s =

null

; buffer =

null

; clientep =

null

; thread.currentthread.

abort()

;}

客戶端**:

void

send

(string content)

catch

(system.net.sockets.socketexception e)

int recv = newclient.

receive

(data)

;//連線伺服器成功

string stringdata = system.text.encoding.unicode.

getstring

(data,

0, recv);if

(stringdata ==

"連線伺服器成功"

)else

}

C 中Socket通訊用法例項詳解

c 中socket通訊用法例項詳解 c 教程 指令碼之家 一 udp方式 伺服器端 staticvoidmain stringargs remote.tostring console.writeline encoding.ascii.getstring data,0,recv stringwelco...

C 中Socket通訊用法例項詳解

一 udp方式 伺服器端 staticvoidmain stringargs remote.tostring console.writeline encoding.ascii.getstring data,0,recv stringwelcome welcome to my test server ...

C 通過socket實現UDP 通訊

接下來我們通過乙個簡單的程式看一下udp通訊的過程。服務端程式 using system using system.collections.generic using system.linq using system.text using system.threading.tasks using s...