C # Socket basics. Welcome!
Test 1:
Using System; using System. Collections. Generic; using System. Text; using System. Net; namespace Socket_Learn {////// @ Author ZJC // This chapter mainly describes the usage of some basic socket classes. The DNS class can obtain the Host Name and IP address list // packet = data block. /// Message is the data unit for exchange and transmission in the network, that is, the data block to be sent by the site at one time. /// The message contains the complete data information to be sent. The length is inconsistent and the length is unlimited and variable. /// The packet is also the unit of network transmission. During transmission, packets, packets, and frames are continuously encapsulated for transmission. // The encapsulation method is to add some information segments, those are the data that is organized by the packet header in a certain format. /// For example, it contains information such as the message type, message version, message length, and message entity. ///Class Program {static void Main (string [] args) {string HostName = Dns. getHostName (); // get this comatrix Uter's name Console. writeLine ("My computer's name = {0}", HostName); // xx pc IPHostEntry ipEntry = Dns. getHostEntry (HostName); // get this conputer's IP address by it's name; IPAddress [] addr = ipEntry. addressList; Console. writeLine ("I have get all the addresses in this computer, show it as follows:"); for (int I = 0; I <addr. length; I ++) {Console. writeLine ("IP address [{0}]: {1}", I, addr [I]. toString (); Console. writeLine ("Address's sort: [{0}], {1}", I, addr [I]. addressFamily. toString (); // addressfamily: ipv4 & ipv6 & LAN} Console. readKey ();}}}
Test 2:
using System;using System.Collections.Generic;using System.Text;using System.Net;using System.Net.Sockets;namespace SocketLearn2{ class Program { static void Main(string[] args) { IPAddress ipaddr = IPAddress.Parse("127.0.0.1"); //IPAddress IPEndPoint ipep = new IPEndPoint(ipaddr,8080); //creat a IPEndPoint Instance Socket test_socket = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp); //creat a instance of socket Console.WriteLine("AddressFamily:{0}",test_socket.AddressFamily); //print our socket's information Console.WriteLine("SocketType:{0}",test_socket.SocketType); Console.WriteLine("ProtocolType:{0}",test_socket.ProtocolType); Console.WriteLine("Blocking:{0}",test_socket.Blocking); test_socket.Blocking = false; //change the attriubutes of Socket's instance Console.WriteLine("Connected:{0}",test_socket.Connected); test_socket.Bind(ipep); //ues Bind() method to connect socket to LocalEndPoint IPEndPoint sock_ipe = (IPEndPoint)test_socket.LocalEndPoint;//if not Bind(),will throw a exception.because test_socket.LocalEndPoint = null! Console.WriteLine("LocalEndPoint:{0}",sock_ipe.ToString()); test_socket.Close(); //close the socket Console.ReadKey(); } }}