Server 端:
namespace lf.socket.clientserver { class Server { static void Main(string[] args) { IPEndPoint ipont = new IPEndPoint(IPAddress.Any, 20); //將IP位址和Port宣告為服務的連接點(所有網路介面卡 IP,20 Port) Socket newsock = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp); //宣告一個Socket通訊介面(使用IPv4協定,通訊類型,通訊協定) newsock.Bind(ipont); //建立本機連線 newsock.Listen(10); //偵測連接(最大連接數) while (true) { Socket client = newsock.Accept(); //宣告一個Socket等於新建立的連線 IPEndPoint clientip = (IPEndPoint)client.RemoteEndPoint; //宣告一個連接點為socket端的連接點 System.Console.WriteLine("Client End Point = " + clientip); //印出遠端IP位址 SocketListener listener = new SocketListener(client); //宣告一個監聽類別SocketListener監聽client訊息 Thread thread = new Thread(new ThreadStart(listener.run)); //宣告一個執行序去跑SocketListener監聽事件 thread.Start(); } } } public class SocketListener { private Socket socket; public SocketListener(Socket socket) { this.socket = socket; //建構元取得遠端socket連線 } public void run() { while (true) { byte[] data = new byte[1024]; //定義一個資料緩衝區接收長度最大為(1024) int len = socket.Receive(data); //接收資料至緩衝區中並回傳成功街收位元數 if (len == 0) break; //若成功接收位元數為0則跳出迴圈 System.Console.WriteLine(Encoding.UTF8.GetString(data,0,len)); //印出編碼後的資料(資料,起始位置,長度) } socket.Close(); } } }
Client 端:
namespace lf.socket.clientserver { class Client { static void Main(string[] args) { IPEndPoint ipont = new IPEndPoint(IPAddress.Parse("127.0.0.1"), 20); //將IP位址和Port宣告為服務的連接點(Server Ip,20 Port) Socket server = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp); //宣告一個Socket通訊介面(使用IPv4協定,通訊類型,通訊協定) server.Connect(ipont); //建立至遠端主機的連接 while (true) { string input = Console.ReadLine(); //接收輸入字串 if (input == "exit")break; //若輸入exit則跳出迴圈 byte[] data = Encoding.UTF8.GetBytes(input); //將字串以UTF8編碼存入緩衝區 server.Send(data); } server.Shutdown(SocketShutdown.Both); //關閉遠端的傳送與接收 server.Close(); //關閉連接 System.Console.Write("Disconnecting from server..."); System.Console.ReadKey(); } } }
沒有留言:
張貼留言