Socket 程式設計

2022-07-13 10:22:16 字數 2819 閱讀 2828

using system; 

using system.collections.generic; 

using system.linq; 

using system.text; 

using system.net; 

using system.net.sockets;  

class program 

static socket clientsocket;  

static void main(string args) 

//將網路端點表示為ip位址和埠 用於socket偵聽時繫結    

clientsocket = new socket(ipep.addressfamily,sockettype.stream,protocoltype.tcp);    

//將socket連線到伺服器    

try 

clientsocket.connect(ipep); 

string outbufferstr; 

byte outbuffer = new byte[1024]; 

byte inbuffer = new byte[1024]; 

while (true) 

//傳送訊息   

outbufferstr = console.readline(); 

outbuffer = encoding.ascii.getbytes(outbufferstr); 

clientsocket.send(outbuffer, outbuffer.length, socketflags.none); 

//接收伺服器端資訊                

clientsocket.receive(inbuffer, 1024, socketflags.none);//如果接收的訊息為空 阻塞 當前迴圈  

console.writeline("伺服器說:"); 

console.writeline(encoding.ascii.getstring(inbuffer)); 

catch 

console.writeline("服務未開啟!"); 

console.readline(); 

using system; 

using system.collections.generic; 

using system.linq; 

using system.text; 

using system.io; 

using system.net; 

using system.net.sockets; 

using system.threading; 

class program 

static socket serversocket; 

static socket clientsocket; 

static thread thread; 

static void main(string args) 

ipendpoint ipep = new ipendpoint(ipaddress.any, 3001); 

serversocket = new socket(ipep.addressfamily, sockettype.stream, protocoltype.tcp); 

serversocket.bind(ipep); 

serversocket.listen(10); 

while (true) 

clientsocket = serversocket.accept(); 

thread = new thread(new threadstart(dowork)); 

thread.start(); 

private static void dowork() 

socket s = clientsocket;//客戶端資訊 

ipendpoint ipendpoint = (ipendpoint)s.remoteendpoint; 

string address = ipendpoint.address.tostring(); 

string port = ipendpoint.port.tostring(); 

console.writeline(address + ":" + port + " 連線過來了"); 

byte inbuffer = new byte[1024]; 

byte outbuffer = new byte[1024]; 

string inbufferstr; 

string outbufferstr; 

try 

while (true) 

s.receive(inbuffer, 1024, socketflags.none);//如果接收的訊息為空 阻塞 當前迴圈  

inbufferstr = encoding.ascii.getstring(inbuffer); 

console.writeline(address + ":" + port + "說:"); 

console.writeline(inbufferstr); 

outbufferstr = console.readline(); 

outbuffer = encoding.ascii.getbytes(outbufferstr); 

s.send(outbuffer, outbuffer.length, socketflags.none); 

catch 

console.writeline("客戶端已關閉!"); 

作者 liyongquanlongliang

socket程式設計

一直以為serversocket accept之後客戶端才能發資訊,實驗後得出如下結論 1 serversocket沒有accept時,client是可以傳送資訊到server端的。2 serversocket accept之後,正在處理訊息時,client也是可以傳送資訊到server端。如果se...

Socket程式設計

對tcp ip udp socket程式設計這些詞你不會很陌生吧?隨著網路技術的發展,這些詞充斥著我們的耳朵。那麼我想問 1.什麼是tcp ip udp?2.socket在 呢?3.socket是什麼呢?4.你會使用它們嗎?什麼是tcp ip udp?tcp ip transmission cont...

socket程式設計

建立socket 建立乙個 socket,它可用於在基於 tcp ip 的網路 如 internet 上通訊。socket s new socket addressfamily.internetwork,sockettype.stream,protocoltype.tcp 若要使用 udp 而不是 ...