C#Socket基础,欢迎来访!
测试一:
using System;
using System.Collections.Generic;
using System.Text;
using System.Net;
namespace Socket_Learn
{
/// <summary>
/// @author ZJC
/// 这章主要学习基本的socket一些类的用法,DNS类可以获得主机的名称和ip地址列表
/// 报文=数据块 。
/// 报文(message)是网络中交换与传输的数据单元,即站点一次性要发送的数据块。
/// 报文包含了将要发送的完整的数据信息,其长短很不一致,长度不限且可变。
/// 报文也是网络传输的单位,传输过程中会不断的封装成分组、包、帧来传输,
/// 封装的方式就是添加一些信息段,那些就是报文头以一定格式组织起来的数据。
/// 比如里面有报文类型,报文版本,报文长度,报文实体等等信息。
/// </summary>
class Program
{
static void Main(string[] args)
{
string HostName = Dns.GetHostName();//get this commputer'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&局域网
}
Console.ReadKey();
}
}
}
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();
}
}
}