Server
usingSystem;usingSystem.Net;usingSystem.Net.Sockets;usingSystem.Text;usingSystem.Threading;namespacemyserver{classSocket_server { Public intPort; PublicIPAddress IP; Private StaticSocket S_socket; Private Static byte[] result =New byte[1024x768]; Public voidInit (stringAddressintPort) { This. Port =Port; IP=Ipaddress.parse (address); } Public voidConnection () {S_socket=Newsockets (AddressFamily.InterNetwork, SocketType.Stream, protocoltype.tcp); S_socket. Bind (Newipendpoint (IP, port)); S_socket. Listen ( -); Thread St=NewThread (Listener); St. Start (); } Private voidListener () { while(true) {Socket C_socket=S_socket. Accept (); C_socket. Send (Encoding.UTF32.GetBytes ("The connection server is successful! ")); Thread CT=NewThread (Receive); Ct. Start (C_socket); } } Private voidReceive (Objectsocket) {Socket C_socket=(socket) socket; while(true) { Try { intnum =C_socket. Receive (result); stringinfo = Encoding.UTF32.GetString (result,0, num); Console.WriteLine (info); C_socket. Send (Encoding.UTF32.GetBytes ("Message Receipts")); } Catch(Exception e) {Console.WriteLine (e.message); Close (); Break; } } } Public voidClose () {s_socket. Shutdown (Socketshutdown.both); S_socket. Close (); } }}
View Code
Server-Console
usingSystem;namespacemyserver{classProgram { Public Static stringInputvalue; Static voidMain (string[] args) {Socket_server Server=NewSocket_server (); Server. Init ("127.0.0.1", the); Server. Connection (); while(Inputvalue! ="Exit") {Inputvalue=Console.ReadLine (); if(Inputvalue = ="Close") {server. Close (); } } } }}
View Code
Client
usingSystem;usingSystem.Collections.Generic;usingSystem.Linq;usingSystem.Net;usingSystem.Net.Sockets;usingSystem.Text;usingSystem.Threading.Tasks;namespaceclient{classsocket_client { Public intPort; PublicIPAddress IP; Private StaticSocket C_socket; Private Static byte[] result =New byte[1024x768]; Public voidInit (stringAddressintPort) { This. Port =Port; IP=Ipaddress.parse (address); } Public voidConnection () {C_socket=Newsockets (AddressFamily.InterNetwork, SocketType.Stream, protocoltype.tcp); Try{c_socket. Connect (Newipendpoint (IP, port)); } Catch(Exception e) {Console.WriteLine (e.message); } ReceiveMessage (); } Public voidReceiveMessage () {intLen = C_socket. Receive (Result,0,1024x768, Socketflags.none); stringmessage = Encoding.UTF32.GetString (result,0, Len); Console.WriteLine (message); } Public voidSendMessage (stringmessage) { byte[] Buff =Encoding.UTF32.GetBytes (message); C_socket. Send (Buff); ReceiveMessage (); } Public voidClose () {c_socket. Close (); } }}
View Code
Client-Console
usingSystem;namespaceclient{classProgram { Public Static stringInputvalue; Static voidMain (string[] args) {socket_client Client=Newsocket_client (); Client. Init ("127.0.0.1", the); Client. Connection (); while(Inputvalue! ="Exit") {Inputvalue=Console.ReadLine (); Client. SendMessage (Inputvalue); if(Inputvalue = ="Close") {client. Close (); } } } }}
View Code
Simple C # socket