簡單Socket通訊

2021-07-25 20:49:46 字數 2278 閱讀 8959

示例程式是同步套接字程式,功能很簡單,只是客戶端發給伺服器一條資訊,伺服器向客戶端返回一條資訊;這裡只是乙個簡單的示例,是乙個最基本的socket程式設計流程,在接下來的文章中,會依次記錄套接字的同步和非同步,以及它們的區別。

下面是示例程式的簡單步驟說明

伺服器端:

第一步:用指定的埠號和伺服器的ip建立乙個endpoint對像;

第二步:建立乙個socket對像;

第三步:用socket對像的bind()方法繫結endpoint;

第四步:用socket對像的listen()方法開始監聽;

第五步:接受到客戶端的連線,用socket對像的accept()方法建立新的socket對像用於和請求的客戶端進行通訊;

第六步:通訊結束後一定記得關閉socket;

服務端**:

[csharp]view plain

copy

using

system;  

using

system.collections.generic;  

using

system.linq;  

using

system.text;  

using

system.threading.tasks;  

using

system.net;  

using

system.net.sockets;  

namespace

server  

", recvstr);

//把客戶端傳來的資訊顯示出來

string

sendstr = 

"ok!client send message successful!"

;  byte

bs = encoding.ascii.getbytes(sendstr);  

temp.send(bs, bs.length, 0);//返回資訊給客戶端

temp.close();  

s.close();  

console.readline();  

}  }  

}  

server結果:

客戶端:

第一步:用指定的埠號和伺服器的ip建立乙個endpoint對像;

第二步:建立乙個socket對像;

第三步:用socket對像的connect()方法以上面建立的endpoint對像做為引數,向伺服器發出連線請求;

第四步:如果連線成功,就用socket對像的send()方法向伺服器傳送資訊;

第五步:用socket對像的receive()方法接受伺服器發來的資訊 ;

第六步:通訊結束後一定記得關閉socket;

c#版 socket程式設計(最簡單的socket通訊功能)

客戶端**:

[csharp]view plain

copy

using

system;  

using

system.collections.generic;  

using

system.linq;  

using

system.text;  

using

system.threading.tasks;  

using

system.net;  

using

system.net.sockets;  

namespace

client  

", recvstr);

//顯示伺服器返回資訊

///一定記著用完socket後要關閉

c.close();  

}  catch

(argumentnullexception e)  

", e);  

}  catch

(socketexception e)  

", e);  

}  console.writeline("press enter to exit"

);  

console.readline();  

}  } 

}  

client端結果:

socket 簡單通訊

服務端 1.建立乙個服務端 import socket phone socket.socket 括號內不輸入,預設為family addressfamily.af inet type socketkind.sock stream proto 0 2.為服務端建立ip位址及埠號 phone.bind ...

簡單socket通訊示例

int socket int domain,int type,int protocol domain 位址族 af unix,af local local communication unix域協議族 af inet ipv4 internet protocols af inet6 ipv6 int...

基於SOCKET簡單通訊程式

主要功能 利用c s模式,可以多台客服機於主機通訊。標頭檔案 ifndef head h define head h include include include include include include include include include include include inc...