DOTNET (C #) Socket Basic Programming

xiaoxiao2021-04-04  241

Socket Basic Programming Service: Using System.net; Using System.Net.sockets; Using System.Text ;. Using System.Thread; Thread Mythread; Socket Socket; // Clean all the resources being used.

Protected Override Void Dispose (Bool Disposing) {Try {Socket.close (); // Release Resource mythread.abort (); // Abort thread} catch {} f (disponents! = null) {components. Dispose ();}} base.Dispose (disposing);} public static IPAddress GetServerIP () {IPHostEntry ieh = Dns.GetHostByName (Dns.GetHostName ()); return ieh.AddressList [0];} private void BeginListen () { IPAddress ServerIp = GetServerIP (); IPEndPoint iep = new IPEndPoint (ServerIp, 8000); socket = new Socket (AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp); byte [] byteMessage = new byte [100]; this.label1 .Text = ip.tostring (); socket.bind (iep); // do while (true) {Try {socket.listen (5); socket newsocket = socket.accept (); newsocket.Receive (byteMessage); string sTime = DateTime.Now.ToShortTimeString (); string msg = sTime ":" "Message from:"; msg = newSocket.RemoteEndPoint.ToString () Encoding.Default.GetString (byteMessage); this.listBox1.Items.Add (msg);} catch (socketexception ex) {this.label1.text = ex.tostri ng ();}} // while (byteMessage = null!);} // begin listening private void button1_Click (object sender, System.EventArgs e) {try {mythread = new Thread (new ThreadStart (BeginListen)); mythread. Start ();} catch (system.exception er) {messagebox.show (Er.Message, "Complete", MessageBoxButtons.ok, MessageBoxicon.Stop);}} client: using system.net; using system.net.sockets ; using System.Text; private void button1_Click (object sender, System.EventArgs e) {BeginSend ();} private void BeginSend () {string ip = this.txtip.Text; string port = this.txtport.Text; IPAddress serverIp = Ipaddress.parse (IP); int serverport = communication.toint32 (port);

IPEndPoint iep = new IPEndPoint (serverIp, serverPort); byte [] byteMessage; // do // {Socket socket = new Socket (AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp); socket.Connect (iep); byteMessage = Encoding.ascii.getbytes; socket.send (ByteMessage); socket.shutdown (socketshutdown.both); socket.close (); //} // while (byteMessage! = Null);} Based on TCP protocol The receiving and receiving end of the TCP protocol Using System.Net.NET.Sockets; // Using the TCPListen class using system.threading; // Use the thread using system.io; // Use StreamReader class INT port = 8000; / / Define the listening port number private thread trthreadread; // creates a thread to listen to the port number, receive information private tcplistener tltcplisten; // Listening port number private bool blistener = true; // Setting the marking, judgment listening state private NetworkStream nsStream; // Create the received elementary stream private StreamReader srRead; private System.Windows.Forms.StatusBar statusBar1; private System.Windows.Forms.Button button1; private System.Windows.Forms.ListBox listBox1; // from Read data private tclient tclient; private void listen () (port); // 8000 port number to initialize TCPListener instance TLTCPListen.Start (); // Start listening statusbar1.text = "Listening ..."; tcclient = tltcplisten.accepttcpclient (); // Request nsstream by TCP connection NSSTream () ; // Get the network base data stream for sending, receive data Srread = new streamreader (nsstream); // to initialize the streamreader instance statusbar1.text = "STREAMREXT =" to get the network base data stream "

While (blistener) // loop listening {string smessage = srread.readline (); // read a row data IF from the network base data stream (SMESSAGE == "STOP") // Determine whether to disconnect TCP connection control Code {TLTCPListen.Stop (); // Close the listening nsstream.close (); // Release the resource srread.close (); statusbar1.text = "Connection is closed!"; Trhetreadread.abort (); // abort thread Return;} string stime = datetime.now.toshostTimeString (); // Get time listbox1.tems.add (stime "" SMESSAGE) when receiving data;}} catch (system.security.securityException) {MessageBox.show ("Listening Failed!", "Error");}} // Start listening Private void button1_click (object sender, system.eventargs e) {ThthreadRead = new Thread (New ThreadStart (Listen)); trthreadread.start (); // Start the thread button1.enabled = false;} // Clean all the resources being used.

Protected Override Void Dispose (Bool Disposing) {TLTCPListen.Stop (); // Close Up NSStream.close (); SRREAD.CLOSE (); // Release Resource THTHREADREAD.ABORT (); // Abort Thread} catch {} if (disponents! = null) {components.dispose ();}}}}} Base.Dispose ();} TCP protocol sending system.net.Sockets; // Used to TCPListen Using System.threading; // Use the thread using system.io; // Use the StreamWriter class using system.net; // use the iPaddress class, the iPhostentry class, etc. Private streamwriter swwriter; // to stream data of data to the network base data NetworkStream nsStream; // create a network based on a streaming private tcpClient tcpClient send data; private System.Windows.Forms.Button button1; private System.Windows.Forms.TextBox textBox1; private System.Windows.Forms.Button button2; private System. Windows.Forms.TextBox textBox2; private System.Windows.Forms.StatusBar statusBar1; private System.Windows.Forms.Label label1; private System.Windows.Forms.Label label2; // made private TCP connection request to the remote host through it BOOL TCPCONNECT = false; // Defines the identifier to indicate whether the TCP connection is established // connection private void button1_click (Object Send ER, System.EventArgs E) {ipaddress ipremote; try {ipremote = ipaddress.parse (textBox1.text);} Catch // Judging the legality of the given IP address {MessageBox.show ("The input IP address is not legal! " , "Error message! ");}}} iphostentry iphost; try {iphost = DNS.Resolve (TextBox1.text);} catCH // Determined IP address The host is online {MessageBox.show (" Remote host is not online! "," error prompt! " "); return;} String ShostName = iphost.hostname; try {tcpclient tclient = new TcpClient (shostname, 8000); // Provide a TCP connection application nSStream = TcpClient.getStream (); // through application And get the network basic data stream of transmitting data swWriter = new streamwriter; // to initialize the streamwriter instance button1.enabled = false; button1.1Abled = true;

转载请注明原文地址:https://www.9cbs.com/read-131715.html

New Post(0)