C#的Socket通讯

服务器代码

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading;
using System.Net.Sockets;
using System.Net;

namespace WindowsFormsApplication1
{
    public class SocketServer
    {
        public static string ReMsg = "";//收到信息
        public  delegate void DtReMsg(string msg);
        public static DtReMsg bGetMsg;
        public static bool bReMsg = false;
        // 创建一个和客户端通信的套接字
        public  static Socket socketwatch = null;
        //定义一个集合,存储客户端信息
        static Dictionary<string, Socket> clientConnectionItems = new Dictionary<string, Socket> { };

        public static void ServeStart()
        {
            //定义一个套接字用于监听客户端发来的消息,包含三个参数(IP4寻址协议,流式连接,Tcp协议)  
            socketwatch = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp);
            //服务端发送信息需要一个IP地址和端口号  
            IPAddress address = IPAddress.Parse("127.0.0.1");
            //将IP地址和端口号绑定到网络节点point上  
            IPEndPoint point = new IPEndPoint(address, 8080);
            //此端口专门用来监听的  

            //监听绑定的网络节点  
            socketwatch.Bind(point);

            //将套接字的监听队列长度限制为20  
            socketwatch.Listen(20);

            //负责监听客户端的线程:创建一个监听线程  
            Thread threadwatch = new Thread(watchconnecting);

            //将窗体线程设置为与后台同步,随着主线程结束而结束  
            threadwatch.IsBackground = true;

            //启动线程     
            threadwatch.Start();        
            Main.SaveMsg("开启监听。。。");
         
        }

        //监听客户端发来的请求  
        static void watchconnecting()
        {
            Socket connection = null;

            //持续不断监听客户端发来的请求     
            while (true)
            {
                try
                {
                    connection = socketwatch.Accept();
                }
                catch (Exception ex)
                {
                    //提示套接字监听异常     
                    Main.SaveMsg(ex.Message);
                    break;
                }

                //获取客户端的IP和端口号  
                IPAddress clientIP = (connection.RemoteEndPoint as IPEndPoint).Address;
                int clientPort = (connection.RemoteEndPoint as IPEndPoint).Port;

                //让客户显示"连接成功的"的信息  
                string sendmsg = "连接服务端成功!\r\n" + "本地IP:" + clientIP + ",本地端口" + clientPort.ToString();
                byte[] arrSendMsg = Encoding.UTF8.GetBytes(sendmsg);
                connection.Send(arrSendMsg);

                //客户端网络结点号  
                string remoteEndPoint = connection.RemoteEndPoint.ToString();
                //显示与客户端连接情况
                Main.SaveMsg("成功与" + remoteEndPoint + "客户端建立连接!\t\n");
                //添加客户端信息  
                clientConnectionItems.Add(remoteEndPoint, connection);

                //IPEndPoint netpoint = new IPEndPoint(clientIP,clientPort); 
                IPEndPoint netpoint = connection.RemoteEndPoint as IPEndPoint;

                //创建一个通信线程      
                ParameterizedThreadStart pts = new ParameterizedThreadStart(recv);
                Thread thread = new Thread(pts);
                //设置为后台线程,随着主线程退出而退出 
                thread.IsBackground = true;
                //启动线程     
                thread.Start(connection);
            
            }
        }
        public static void SendMsg(string str)
        {
           
            byte[] arrSendMsg = Encoding.UTF8.GetBytes(str);
            if(clientConnectionItems.Count>0)
            {
                foreach (KeyValuePair< string, Socket> kvp in clientConnectionItems)
                {
                    kvp.Value.Send(arrSendMsg);

                }               
            }
        }
        /// <summary>
        /// 接收客户端发来的信息,客户端套接字对象
        /// </summary>
        /// <param name="socketclientpara"></param>    
        static void recv(object socketclientpara)
        {
            Socket socketServer = socketclientpara as Socket;

            while (true)
            {
                //创建一个内存缓冲区,其大小为1024*1024字节  即1M     
                byte[] arrServerRecMsg = new byte[1024 * 1024];
                //将接收到的信息存入到内存缓冲区,并返回其字节数组的长度    
                try
                {
                    int length = socketServer.Receive(arrServerRecMsg);
                    bReMsg = true;
                    //将机器接受到的字节数组转换为人可以读懂的字符串     
                    string strSRecMsg = Encoding.UTF8.GetString(arrServerRecMsg, 0, length);
                    if (bGetMsg != null)
                        bGetMsg(strSRecMsg);
                    ReMsg = strSRecMsg;
                    //将发送的字符串信息附加到文本框txtMsg上     
                    Main.SaveMsg("客户端:" + socketServer.RemoteEndPoint + ",time:" + GetCurrentTime() + "\r\n" + strSRecMsg + "\r\n\n");

                    socketServer.Send(Encoding.UTF8.GetBytes("测试server 是否可以发送数据给client "));
                }
                catch (Exception ex)
                {
                    clientConnectionItems.Remove(socketServer.RemoteEndPoint.ToString());

                    Main.SaveMsg("Client Count:" + clientConnectionItems.Count);

                    //提示套接字监听异常  
                    Main.SaveMsg("客户端" + socketServer.RemoteEndPoint + "已经中断连接" + "\r\n" + ex.Message + "\r\n" + ex.StackTrace + "\r\n");
                    //关闭之前accept出来的和客户端进行通信的套接字 
                    socketServer.Close();
                    break;
                }
            }
        }

        ///      
        /// 获取当前系统时间的方法    
        /// 当前时间     
        static DateTime GetCurrentTime()
        {
            DateTime currentTime = new DateTime();
            currentTime = DateTime.Now;
            return currentTime;
        }
    }
}

客户端代码

using System;
using System.Collections.Generic;
using System.Linq;
using System.Net;
using System.Net.Sockets;
using System.Text;
using System.Threading;

namespace TCPClinent
{
    class Program
    {
        /// <summary>
        /// Remote Setting, iM Simulator's IP And Port.
        /// </summary>
        static IPEndPoint RemoteSetting = new IPEndPoint(IPAddress.Parse("127.0.0.1"), 9999);

        /// <summary>
        /// TCP/IP Clinent
        /// </summary>
        static Socket Client { get; } = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp);

        static void Main(string[] args)
        {
            Console.WriteLine("This Program Build With C# .Net Framework 4.0");
            Console.WriteLine("=============================================");
            Console.WriteLine("First, Open iM Simulator");
            Console.WriteLine("Then Open This Program");
            Console.WriteLine("You Can Enter Some Message(Ex. 'Hello'), The Program Will Send Your Message To Remote");
            Console.WriteLine("=============================================");
            try
            {
                Client.Connect(RemoteSetting);
            }
            catch (Exception ex)
            {
                Console.WriteLine();
                Console.WriteLine($"[XX]Throw Exception: {ex.Message}");
            }

            // Creat Other Thread For Receive Data From iM Simulator
            CreatDataReceiveThread(Client);

            // The Main Thread Used For Send Message
            while (true)
            {
                try
                {
                    // Read Inputs And Append "\r\n"(new line)
                    string message = Console.ReadLine() + "\r\n";
                    // Encode With ASCII
                    byte[] data = Encoding.ASCII.GetBytes(message);
                    // Send
                    Client.Send(data);
                }
                catch (Exception ex)
                {
                    Console.WriteLine();
                    Console.WriteLine($"[XX]Throw Exception: {ex.Message}");
                    break;
                }
            }

            // Stop The Program
            Console.WriteLine("Enter Any Key For Exist...");
            Console.ReadKey();
        }

        /// <summary>
        /// Build A Thread For Received Data And Print
        /// </summary>
        /// <param name="client"></param>
        private static void CreatDataReceiveThread(Socket client)
        {
            var thread = new Thread(() =>
            {
                while (true)
                {
                    try
                    {
                        // Creat A Buffer For Received Data
                        int bufferSize = 2048;
                        byte[] buffer = new byte[bufferSize];
                        // Wait And Received
                        int realDataBytes = Client.Receive(buffer);
                        // Trim Buffer Size
                        buffer = buffer.Take(realDataBytes).ToArray();
                        // Decode With ASCII
                        string message = Encoding.ASCII.GetString(buffer);
                        // Print The Message
                        Console.WriteLine($"[>>] {message}");
                    }
                    catch (Exception ex)
                    {
                        Console.WriteLine();
                        Console.WriteLine($"[XX]Throw Exception: {ex.Message}");
                        break;
                    }
                }
            })
            { IsBackground = true, Name = "Received Data Thread" };
            thread.Start();
        }
    }
}
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值