TCP交互

来源:互联网 发布:电视直播用哪个软件 编辑:程序博客网 时间:2024/06/05 10:37

局域网内实现两个机器之间的信息传输功能

主客户端,接收方

using System;

using System.Collections.Generic;

using System.Linq;

using System.Net;

using System.Net.NetworkInformation;

using System.Net.Sockets;

using System.Text;

using System.Threading;

using System.Threading.Tasks;

 

namespace TcpServer

{

    classProgram

    {

        staticvoid Main(string[] args)

        {

            Server server =newServer();

            server.StartUp();

 

            while (true)

            {

                string str =Console.ReadLine();

            }

        }

    }

 

    publicclassServer

    {

        //配置相关

        privatestring _ip ="192.168.30.34";

        privateint _port = 10000;

        //服务器套接字

        privateSocket _server;

        //接受客户端连接的线程,因为Accept是一个阻塞线程的方法,而且此方法还需要循环执行

        privateThread _acceptClientConnectThread;

        //所有已经连接的客户端

        privateList<Socket> _clientList =newList<Socket>();

        ///<summary>

        ///启动服务器 =建立流式套接字 +配置本地文件

        ///</summary>

        publicvoid StartUp()

        {

            try

            {

                //建立套接字寻址方案,套接字类型,协议类型

                _server = newSocket(AddressFamily.InterNetwork,SocketType.Stream,ProtocolType.Tcp);

                // _server = newSocket(AddressFamily.InterNetwork, SocketType.Dgram, ProtocolType.Udp);

                //配置本地地址

                EndPoint endPoint =newIPEndPoint(GetIpv4(NetworkInterfaceType.Ethernet), _port);

                _server.Bind(endPoint);

                //监听和接受客户端请求

                _server.Listen(30);

                //接受客户端连接

                _acceptClientConnectThread =newThread(AcceptClientConnect);

               _acceptClientConnectThread.Start();

 

                Console.WriteLine("{0}:{1} StartUp...", _ip, _port);

            }

            catch (Exception e)

            {

                Console.WriteLine(e.Message);

            }

        }

        ///<summary>

        ///接受客户端连接

        ///</summary>

        publicvoid AcceptClientConnect()

        {

            while (true)

            {

                try

                {

                    //接受客户端连接

                    Socket clientSocket = _server.Accept();

                    //维护一个客户端在线列表

                   _clientList.Add(clientSocket);

                    //获取客户端的网络地址标识

                    IPEndPoint clientEndPoint = clientSocket.RemoteEndPointasIPEndPoint;

                    //输出一个地址和端口

                    Console.WriteLine("{0}:{1} Connect...", clientEndPoint.Address.ToString(),clientEndPoint.Port);

 

                    //接受客户端消息的线程

                    Thread acceptClientMsg =newThread(AcceptMsg);

                   acceptClientMsg.Start(clientSocket);

                }

                catch (Exception e)

                {

                    Console.WriteLine(e.Message);

                }

            }

        }

        ///<summary>

        ///接收消息

        ///</summary>

        ///<paramname="obj"></param>

        publicvoid AcceptMsg(object obj)

        {

            //强转为Socket类型

            Socket client = objasSocket;

            //字节数组 接受传来的消息

            byte[] buffer =newbyte[client.ReceiveBufferSize];

            //获取客户端的网络地址标识

            IPEndPoint clientEndPoint = client.RemoteEndPointasIPEndPoint;

 

            try

            {

                while (true)

                {

                    //接收消息

                    int len = client.Receive(buffer);

                    string str =Encoding.UTF8.GetString(buffer, 0, len);

                    //哪个里面的地址的哪个端口发了什么消息

                    Console.WriteLine("Receive {0}:{1}:{2}", clientEndPoint.Address.ToString(),_port, str);

                }

            }

            catch (SocketException e)

            {

                Console.WriteLine(e.Message);

                _clientList.Remove(client);

            }

        }

        ///<summary>

        ///给摸一个客户端发送信息

        ///</summary>

        ///<paramname="str"></param>

        ///<param name="client"></param>

        publicvoid Send(string str,Socket client)

        {

            try

            {

                //string => byte[]

                byte[] strBytes =Encoding.UTF8.GetBytes(str);

                client.Send(strBytes);

            }

            catch (Exception e)

            {

                Console.WriteLine(e.Message);

            }

        }

        ///<summary>

        ///发送给所有人

        ///</summary>

        ///<paramname="str"></param>

        publicvoid SendAll(string str)

        {

            for (int i = 0; i < _clientList.Count;i++)

            {

                Send(str, _clientList[i]);

            }

        }

        publicIPAddress GetIpv4(NetworkInterfaceType type)

        {

            NetworkInterface[] networkInterfaces =NetworkInterface.GetAllNetworkInterfaces();

            for (int i = 0; i <networkInterfaces.Length; i++)

            {

                if (type == networkInterfaces[i].NetworkInterfaceType &&networkInterfaces[i].OperationalStatus ==OperationalStatus.Up)

                {

                    UnicastIPAddressInformationCollection ips =networkInterfaces[i].GetIPProperties().UnicastAddresses;

                    foreach (UnicastIPAddressInformation itemin ips)

                    {

                        if (item.Address.AddressFamily ==AddressFamily.InterNetwork)

                        {

                            return item.Address;

                        }

                    }

                }

            }

            returnnull;

        }

        ///<summary>

        ///关闭套接字

        ///</summary>

        publicvoid Close()

        {

            if (_clientList.Count > 0)

            {

                for (int i = 0; i < _clientList.Count;i++)

                {

                    _clientList[i].Close();

                }

            }

            _clientList.Clear();

            _server.Close();

            _acceptClientConnectThread.Abort();

        }

    }

}

 

输入方

using System;

using System.Collections.Generic;

using System.Linq;

using System.Net.Sockets;

using System.Text;

using System.Threading;

using System.Threading.Tasks;

 

namespace TcpClient

{

    classProgram

    {

        staticvoid Main(string[] args)

        {

            Client client =newClient();

            client.StartUp();

            while (true)

            {

                string str =Console.ReadLine();

                client.Send(str);

            }

        }

    }

    publicclassClient

    {

        privateSocket _client;

        privateThread _acceptServerMsg;

 

        publicvoid StartUp()

        {

            try

            {

                _client = newSocket(AddressFamily.InterNetwork,SocketType.Stream,ProtocolType.Tcp);

                //客户端连接

                _client.Connect("192.168.30.34", 10000);

                //接受消息的线程

                _acceptServerMsg =newThread(AcceptServerMsg);

                _acceptServerMsg.Start();

            }

            catch (Exception e)

            {

                Console.WriteLine(e.Message);

            }

        }

        publicvoidAcceptServerMsg()

        {

            byte[] buffer =newbyte[1024 * 64];

            while (true)

            {

                try

                {

                    int len = _client.Receive(buffer);

                    string str =Encoding.UTF8.GetString(buffer, 0, len);

                    Console.WriteLine("Reveive Msg From Server : {0}",str);

                }

                catch (Exception e)

                {

                    Console.WriteLine(e.Message);

                }

            }

        }

        ///<summary>

        ///发送消息

        ///</summary>

        ///<paramname="str"></param>

        publicvoid Send(string str)

        {

            try

            {

                byte[] strBytes =Encoding.UTF8.GetBytes(str);

                _client.Send(strBytes);

            }

            catch (Exception e)

            {

                Console.WriteLine(e.Message);

            }

        }

        publicvoid Close()

        {

            if (_client.Connected)

            {

                _client.Close();

            }

            _acceptServerMsg.Abort();

        }

    }

}

 

两个c#程序,先运行主客户端Server





原创粉丝点击