使用Socket通信--测试叫号

服务端程序:

using System;
using System.Net;
using System.Net.Sockets;
using System.Speech.Synthesis;
using System.Text;
using System.Threading;
using System.Windows.Forms;

namespace CallServer
{
    public partial class Form1 : Form
    {
        public Form1()
        {
            InitializeComponent();

            Control.CheckForIllegalCrossThreadCalls = false;
        }

        /// <summary>
        /// 等待客户端的连接 并且创建与之通信的Socket
        /// </summary>
        Socket socketSend;
        void Listen(object o)
        {
            try
            {
                Socket socketWatch = o as Socket;
                while (true)
                {
                    socketSend = socketWatch.Accept();//等待接收客户端连接
                    ShowMsg(socketSend.RemoteEndPoint.ToString() + ":" + "连接成功!");
                    //开启一个新线程,执行接收消息方法
                    Thread r_thread = new Thread(Received);
                    r_thread.IsBackground = true;
                    r_thread.Start(socketSend);
                }
            }
            catch { }
        }
        /// <summary>
        /// 服务器端不停的接收客户端发来的消息
        /// </summary>
        /// <param name="o"></param>
        void Received(object o)
        {
            try
            {
                Socket socketSend = o as Socket;
                while (true)
                {
                    //客户端连接服务器成功后,服务器接收客户端发送的消息
                    byte[] buffer = new byte[1024 * 1024 * 3];
                    //实际接收到的有效字节数
                    int len = socketSend.Receive(buffer);
                    if (len == 0)
                    {
                        break;
                    }
                    string str = Encoding.UTF8.GetString(buffer, 0, len);
                    ShowMsg(socketSend.RemoteEndPoint + ":" + str);
                    //叫号
                    SpeakStr(str);
                }
            }
            catch { }
        }
        /// <summary>
        /// 服务器向客户端发送消息
        /// </summary>
        /// <param name="str"></param>
        void Send(string str)
        {
            byte[] buffer = Encoding.UTF8.GetBytes(str);
            socketSend.Send(buffer);
        }

        StringBuilder buf = new StringBuilder();
        void ShowMsg(string msg)
         {
            buf.Append(msg);
            buf.Append("

");
            this.txtContent.Text = buf.ToString();
         }

        private void SpeakStr(string content)
        {
            //方式一
            //SpeechVoiceSpeakFlags flag = SpeechVoiceSpeakFlags.SVSFlagsAsync;
            //SpVoice voice = new SpVoice();
            //var aa = voice.GetVoices(string.Empty, string.Empty);
            //voice.Voice = voice.GetVoices(string.Empty, string.Empty).Item(0);
            //voice.Rate = 1;//阅读速度
            //方式二
            SpeechSynthesizer hello = new SpeechSynthesizer();
            //string str = "请A001号到第一检查室检查";
            hello.Volume = 10;
            hello.Rate = -5;//-10-10,值越小,语速越慢
            hello.Speak(content);  //Speak(string),Speak加上字符串类型的参数

            //Item(0)单词男声Sam
            //Item(1)单词男声Mike
            //Item(2)单词女声Mary
            //Item(3)中文发音,如果是英文,就依单词字母一个一个发音
            //voice.Speak(content, flag);
        }

        private void btnSend_Click(object sender, EventArgs e)
        {
            Send(this.txtSendMessage.Text.Trim()+"
");
        }

        private void btnStartListener_Click(object sender, EventArgs e)
        {
            CreateListener();
        }

        private void CreateListener()
        {
            try
            {
                //点击开始监听时 在服务端创建一个负责监听IP和端口号的Socket
                Socket socketWatch = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp);
                IPAddress ip = IPAddress.Any;
                //创建对象端口
                IPEndPoint point = new IPEndPoint(ip, Convert.ToInt32(txtPort.Text));

                socketWatch.Bind(point);//绑定端口号
                ShowMsg("监听成功!");
                socketWatch.Listen(10);//设置监听

                //创建监听线程
                Thread thread = new Thread(Listen);
                thread.IsBackground = true;
                thread.Start(socketWatch);
            }
            catch { }
        }

    }
}

客户端程序:

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

namespace CallClient
{
    public partial class Form1 : Form
    {
        public Form1()
        {
            InitializeComponent();
            Control.CheckForIllegalCrossThreadCalls = false;
        }

        Socket socketSend;
        private void btnStartListener_Click(object sender, EventArgs e)
        {
            try
            {
                //创建客户端Socket,获得远程ip和端口号
                socketSend = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp);
                IPAddress ip = IPAddress.Parse(this.txtIP.Text);
                IPEndPoint point = new IPEndPoint(ip, Convert.ToInt32(this.txtPort.Text));

                socketSend.Connect(point);
                ShowMsg("连接成功!");
                //开启新的线程,不停的接收服务器发来的消息
                Thread c_thread = new Thread(Received);
                c_thread.IsBackground = true;
                c_thread.Start();
            }
            catch (Exception)
            {
                ShowMsg("IP或者端口号错误...");
            }
        }

        void ShowMsg(string str)
        {
            this.txtContent.AppendText(str + "
");
        }

        /// <summary>
        /// 接收服务端返回的消息
        /// </summary>
        void Received()
        {
            while (true)
            {
                try
                {
                    byte[] buffer = new byte[1024 * 1024 * 3];
                    //实际接收到的有效字节数
                    int len = socketSend.Receive(buffer);
                    if (len == 0)
                    {
                        break;
                    }
                    string str = Encoding.UTF8.GetString(buffer, 0, len);
                    ShowMsg(socketSend.RemoteEndPoint + ":" + str);
                }
                catch { }
            }
        }

        private void btnSend_Click(object sender, EventArgs e)
        {
            try
             {
                 string msg = this.txtSendMessage.Text.Trim()+"

";
                 byte[] buffer = new byte[1024 * 1024 * 3];
                 buffer = Encoding.UTF8.GetBytes(msg);
                 socketSend.Send(buffer);
             }
             catch { }
        }

    }
}

注:需先启动服务端程序,客户端程序发送消息时,需和服务端进行一次握手(个人理解)---确认连接成功......

原文地址:https://www.cnblogs.com/YYkun/p/9481232.html