标签:
1.按惯例先来介绍下socket
Windows中的很多东西都是从Unix领域借鉴过来的,Socket也是一样。在Unix中,socket代表了一种文件描述符(在Unix中一切都是以文件为单位),而这里这个描述符则是用于描述网络访问的。什么意思呢?就是程序员可以通过socket来发送和接收网络上的数据。你也可以理解成是一个API。有了它,你就不用直接去操作网卡了,而是通过这个接口,这样就省了很多复杂的操作。
在C#中,MS为我们提供了 System.Net.Sockets 命名空间,里面包含了Socket类。
2.有了socket,那就可以用它来访问网络了
不过你不要高兴得太早,要想访问网络,还得有些基本的条件(和编程无关的我就不提了):a. 要确定本机的IP和端口,socket只有与某一IP和端口绑定,才能发挥强大的威力。b. 得有协议吧(否则谁认得你这发送到网络的是什么呀)。想要复杂的,我们可以自己来定协议。但是这个就不在这篇里提了,我这里介绍两种大家最熟悉不过的协议:TCP & UDP。(别说你不知道,不然...不然...我不告诉你)
如果具备了基本的条件,就可以开始用它们访问网络了。来看看步骤吧:
a. 建立一个套接字
b. 绑定本机的IP和端口
c. 如果是TCP,因为是面向连接的,所以要利用ListenO()方法来监听网络上是否有人给自己发东西;如果是UDP,因为是无连接的,所以来者不拒。
d. TCP情况下,如果监听到一个连接,就可以使用accept来接收这个连接,然后就可以利用Send/Receive来执行操作了。而UDP,则不需要accept, 直接使用SendTo/ReceiveFrom来执行操作。(看清楚哦,和TCP的执行方法有区别,因为UDP不需要建立连接,所以在发送前并不知道对方的IP和端口,因此需要指定一个发送的节点才能进行正常的发送和接收)
e. 如果你不想继续发送和接收了,就不要浪费资源了。能close的就close吧。
如果看了上面文字,你还不清楚的话,就来看看图好了:

面向连接的套接字系统调用时序

无连接的套接字系统调用时序
using System;using System.Collections.Generic;using System.Linq;using System.Text;using System.Net.Sockets;using System.Net;namespace TCPServer{class server{[STAThread]static void Main(string[] args){//// TODO: 在此处添加代码以启动应用程序//int recv;//用于表示客户端发送的信息长度byte[] data = new byte[1024];//用于缓存客户端所发送的信息,通过socket传递的信息必须为字节数组IPEndPoint ipep = new IPEndPoint(IPAddress.Any, 9050);//本机预使用的IP和端口Socket newsock = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp);newsock.Bind(ipep);//绑定newsock.Listen(10);//监听Console.WriteLine("waiting for a client");Socket client = newsock.Accept();//当有可用的客户端连接尝试时执行,并返回一个新的socket,用于与客户端之间的通信IPEndPoint clientip = (IPEndPoint)client.RemoteEndPoint;Console.WriteLine("connect with client:" + clientip.Address + " at port:" + clientip.Port);string welcome = "welcome here!";data = Encoding.ASCII.GetBytes(welcome);client.Send(data, data.Length, SocketFlags.None);//发送信息while (true){//用死循环来不断的从客户端获取信息data = new byte[1024];recv = client.Receive(data);Console.WriteLine("recv=" + recv);if (recv == 0)//当信息长度为0,说明客户端连接断开break;Console.WriteLine(Encoding.ASCII.GetString(data, 0, recv));client.Send(data, recv, SocketFlags.None);}Console.WriteLine("Disconnected from" + clientip.Address);client.Close();newsock.Close();}}}
using System.Net;using System.Net.Sockets;using System.Text;using System.Threading;namespace TCPClient{class tcpclient{[STAThread]static void Main(string[] args){//// TODO: 在此处添加代码以启动应用程序//byte[] data = new byte[1024];Socket newclient = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp);Console.Write("please input the server ip:");string ipadd = Console.ReadLine();Console.WriteLine();Console.Write("please input the server port:");int port = Convert.ToInt32(Console.ReadLine());IPEndPoint ie = new IPEndPoint(IPAddress.Parse(ipadd), port);//服务器的IP和端口try{//因为客户端只是用来向特定的服务器发送信息,所以不需要绑定本机的IP和端口。不需要监听。newclient.Connect(ie);}catch (SocketException e){Console.WriteLine("unable to connect to server");Console.WriteLine(e.ToString());return;}// 读取从server传回来的数据,并计算有多少个数据int recv = newclient.Receive(data);// 将缓存data中的数据重新编码成ASCII的string字符串string stringdata = Encoding.ASCII.GetString(data, 0, recv);// 打印出穿回来的字符串Console.WriteLine(stringdata);// 开始与服务器端的通信while (true){string input = Console.ReadLine();if (input == "exit")break;// 将input编码成ASCII的Bytes并发送到服务端newclient.Send(Encoding.ASCII.GetBytes(input));// 重置缓存区data = new byte[1024];// 重新从服务器端获取一次缓存区的数据recv = newclient.Receive(data);stringdata = Encoding.ASCII.GetString(data, 0, recv);// 打印出数据Console.WriteLine(stringdata);}Console.WriteLine("disconnect from sercer");newclient.Shutdown(SocketShutdown.Both);newclient.Close();}}}
标签:
原文地址:http://www.cnblogs.com/weloveshare/p/a4b35726915f884b4d1e87127a714e17.html