Socket

Socket(套接字)编程(Tcp)

1.基于Tcp协议的Socket通讯类似于B/S架构,面向连接,但不同的是服务器端可以向客户端主动推送消息。

使用Tcp协议通讯需要具备以下几个条件:

(1).建立一个套接字(Socket) (2).绑定服务器端IP地址及端口号--服务器端 (3).利用Listen()方法开启监听--服务器端 (4).利用Accept()方法尝试与客户端建立一个连接--服务器端 (5).利用Connect()方法与服务器建立连接--客户端 (6).利用Send()方法向建立连接的主机发送消息 (7).利用Recive()方法接受来自建立连接的主机的消息(可靠连接)

TcpServer

public static void TcpServer(IPEndPoint serverIP)
{
    Console.WriteLine("客户端Tcp连接模式");
    Socket tcpServer = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp);
    tcpServer.Bind(serverIP);
    tcpServer.Listen(100);
    Console.WriteLine("开启监听...");
    new Thread(() =>
    {
        while (true)
        {
            try
            {
                TcpRecive(tcpServer.Accept());
            }
            catch (Exception ex)
            {
                Console.WriteLine(string.Format("出现异常:{0}", ex.Message));
                break;
            }
        }
    }).Start();
    Console.WriteLine("\n\n输入\"Q\"键退出。");
    ConsoleKey key;
    do
    {
        key = Console.ReadKey(true).Key;
    } while (key != ConsoleKey.Q);
    tcpServer.Close();
}

TcpRecive

public static void TcpRecive(Socket tcpClient)
{
    new Thread(() =>
    {
        while (true)
        {
            byte[] data = new byte[1024];
            try
            {
                int length = tcpClient.Receive(data);
            }
            catch (Exception ex)
            {
                Console.WriteLine(string.Format("出现异常:{0}", ex.Message));
                break;
            }
            Console.WriteLine(string.Format("收到消息:{0}", Encoding.UTF8.GetString(data)));
            string sendMsg = "收到消息!";
            tcpClient.Send(Encoding.UTF8.GetBytes(sendMsg));
        }
    }).Start();
}

TcpClient

public static void TcpServer(IPEndPoint serverIP)
{
    Console.WriteLine("客户端Tcp连接模式");
    Socket tcpClient = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp);
    try
    {
        tcpClient.Connect(serverIP);
    }
    catch (SocketException e)
    {
        Console.WriteLine(string.Format("连接出错:{0}", e.Message));
        Console.WriteLine("点击任何键退出!");
        Console.ReadKey();
        return;
    }
    Console.WriteLine("客户端:client-->server");
    string message = "我上线了...";
    tcpClient.Send(Encoding.UTF8.GetBytes(message));
    Console.WriteLine(string.Format("发送消息:{0}", message));
    new Thread(() =>
    {
        while (true)
        {
            byte[] data = new byte[1024];
            try
            {
                int length = tcpClient.Receive(data);
            }
            catch (Exception ex)
            {
                Console.WriteLine(string.Format("出现异常:{0}", ex.Message));
                break;
            }
            Console.WriteLine(string.Format("{0} 收到消息:{1}", DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss"), Encoding.UTF8.GetString(data)));
        }
    }).Start();
    Console.WriteLine("\n\n输入\"Q\"键退出。");
    ConsoleKey key;
    do
    {
        key = Console.ReadKey(true).Key;
    } while (key != ConsoleKey.Q);
    tcpClient.Close();
}

一个最简单的服务器客户端Socket TCP通信示例

服务端

using System;
using System.Net;
using System.Net.Sockets;
using System.Text;

namespace SocketTCP
{
    class MainClass
    {
        public static void Main (string[] args)
        {
            //1.创建Socket
            Socket socket = new Socket (AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp);
            //2.绑定ip地址和端口号
            IPAddress ip = new IPAddress (new byte[]{192,168,1,201});
            EndPoint ep = new IPEndPoint (ip, 7788);//对ip和端口做一层封装
            socket.Bind (ep);//向操作系统申请一个可用的ip和端口进行通信
            //3.开始监听
            socket.Listen (100);//表示最大连接数

            Console.WriteLine ("服务端已就绪,等待服务端连接");

            Socket clientSocket = socket.Accept ();//暂停当前线程,直到有客户端来连接服务端,才会进行下面的流程

            Console.WriteLine ("一个客户端连接成功");
            string sendMessage = "Welcome to server";
            //将要发送的数据转成byte数组
            byte[] data = Encoding.UTF8.GetBytes (sendMessage);
            clientSocket.Send (data);
            Console.WriteLine ("向客户端发送欢迎信息");

            byte[] data2 = new byte[1024];//创建一个二进制数组来接收发来的信息
            int length = clientSocket.Receive (data2);//表示接收到数据的字节数
            string recivedMessage = Encoding.UTF8.GetString(data2,0,length);//把接收到的数据做一个转化
            Console.Write("服务的收到的消息:" + recivedMessage);

            Console.ReadKey ();
        }
    }
}

客户端

using System;
using System.Net;
using System.Net.Sockets;
using System.Text;

namespace SocketTCPClient
{
    class MainClass
    {
        public static void Main (string[] args)
        {
            //1.建立Socket
            Socket socket = new Socket (AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp);

            //2.发起建立连接的请求
            IPAddress ip = new IPAddress(new Byte[]{192,168,1,201});
            EndPoint ep = new IPEndPoint (ip, 7788);
            socket.Connect (ep);//通过ip和端口连接到一个服务器
            byte[] data = new byte[1024];//创建一个二进制数组来接收发来的信息
            int length = socket.Receive (data);//表示接收到数据的字节数
            string recivedMessage = Encoding.UTF8.GetString(data,0,length);//把接收到的数据做一个转化
            Console.WriteLine("客户端收到的消息:" + recivedMessage);

            string sendMessage = Console.ReadLine ();
            Console.WriteLine ("客户端说:" + sendMessage);
            socket.Send (Encoding.UTF8.GetBytes (sendMessage));

            Console.ReadKey ();
        }
    }
}

Socket(套接字)编程(Udp)

基于Udp协议是无连接模式通讯,占用资源少,响应速度快,延时低。至于可靠性,可通过应用层的控制来满足。(不可靠连接)

(1).建立一个套接字(Socket) (2).绑定服务器端IP地址及端口号--服务器端 (3).通过SendTo()方法向指定主机发送消息(需提供主机IP地址及端口) (4).通过ReciveFrom()方法接收指定主机发送的消息(需提供主机IP地址及端口)

UdpServer

public static void UdpServer(IPEndPoint serverIP)
{
    Console.WriteLine("客户端Udp模式");
    Socket udpServer = new Socket(AddressFamily.InterNetwork, SocketType.Dgram, ProtocolType.Udp);
    udpServer.Bind(serverIP);
    IPEndPoint ipep = new IPEndPoint(IPAddress.Any, 0);
    EndPoint Remote = (EndPoint)ipep;
    new Thread(() =>
    {
        while (true)
        {
            byte[] data = new byte[1024];
            try
            {
                int length = udpServer.ReceiveFrom(data, ref Remote);//接受来自服务器的数据
            }
            catch (Exception ex)
            {
                Console.WriteLine(string.Format("出现异常:{0}", ex.Message));
                break;
            }
            Console.WriteLine(string.Format("{0} 收到消息:{1}", DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss"), Encoding.UTF8.GetString(data)));
            string sendMsg = "收到消息!";
            udpServer.SendTo(Encoding.UTF8.GetBytes(sendMsg), SocketFlags.None, Remote);
        }
    }).Start();
    Console.WriteLine("\n\n输入\"Q\"键退出。");
    ConsoleKey key;
    do
    {
        key = Console.ReadKey(true).Key;
    } while (key != ConsoleKey.Q);
    udpServer.Close();
}

UdpClient

public static void UdpClient(IPEndPoint serverIP)
{
    Console.WriteLine("客户端Udp模式");
    Socket udpClient = new Socket(AddressFamily.InterNetwork, SocketType.Dgram, ProtocolType.Udp);
    string message = "我上线了...";
    udpClient.SendTo(Encoding.UTF8.GetBytes(message), SocketFlags.None, serverIP);
    Console.WriteLine(string.Format("发送消息:{0}", message));
    IPEndPoint sender = new IPEndPoint(IPAddress.Any, 0);
    EndPoint Remote = (EndPoint)sender;
    new Thread(() =>
    {
        while (true)
        {
            byte[] data = new byte[1024];
            try
            {
                int length = udpClient.ReceiveFrom(data, ref Remote);//接受来自服务器的数据
            }
            catch (Exception ex)
            {
                Console.WriteLine(string.Format("出现异常:{0}", ex.Message));
                break;
            }
            Console.WriteLine(string.Format("{0} 收到消息:{1}", DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss"), Encoding.UTF8.GetString(data)));
        }
    }).Start();
    Console.WriteLine("\n\n输入\"Q\"键退出。");
    ConsoleKey key;
    do
    {
        key = Console.ReadKey(true).Key;
    } while (key != ConsoleKey.Q);
    udpClient.Close();
}

一个最简单的服务器客户端Socket UDP通信示例

服务端

using System;
using System.Net;
using System.Net.Sockets;
using System.Text;
using System.Threading;

namespace SocketUDPServer
{
    class MainClass
    {
        static Socket serverSocket;

        public static void Main (string[] args)
        {
            serverSocket = new Socket (AddressFamily.InterNetwork, SocketType.Dgram, ProtocolType.Udp);
            serverSocket.Bind(new IPEndPoint(IPAddress.Parse("192.168.1.201"),7788));

            new Thread (ReceiveMessage){ IsBackground = true }.Start ();

            Console.ReadKey ();
        }

        static void ReceiveMessage() {
            //接受数据
            while (true) {
                EndPoint endPoint = new IPEndPoint(IPAddress.Any,0);
                byte[] data = new byte[1024];
                int length = serverSocket.ReceiveFrom (data, ref endPoint);
                string message = Encoding.UTF8.GetString (data,0,length);
                Console.WriteLine ("接受到来自" + (endPoint as IPEndPoint).Address + "  " + (endPoint as IPEndPoint).Port + "的消息:" + message);
            }
        }
    }
}

客户端

using System;
using System.Net.Sockets;
using System.Net;
using System.Text;

namespace SocketUDPClient
{
    class MainClass
    {
        public static void Main (string[] args)
        {
            Socket clientSocket = new Socket (AddressFamily.InterNetwork, SocketType.Dgram, ProtocolType.Udp);

            while (true) {
                EndPoint endPoint = new IPEndPoint (IPAddress.Parse ("192.168.1.201"), 7788);
                string message = Console.ReadLine ();
                byte[] data = Encoding.UTF8.GetBytes (message);
                clientSocket.SendTo (data, endPoint);
            }


            Console.ReadKey ();
        }
    }
}

results matching ""

    No results matching ""