码迷,mamicode.com
首页 > Windows程序 > 详细

基于C#局域网语音聊天

时间:2018-11-10 22:46:58      阅读:240      评论:0      收藏:0      [点我收藏+]

标签:orm   list   eve   sock   res   app   +=   引入   文本   

基?于?C?#?局?域?网?语?音?聊?天?室?,?可?实?现?文?本?消?息?的?发?送?、?接?收?及?语?音?聊?天?,?是?一?个?很?不?错?的?,?适?合?初?学?者?的?软?件?开?发?项?目?。(未经验证)
——http://wenku.baidu.com/link?url=f1gmOU2J04pf3wB9tldwuZS3VsXWYlmhUPSwdLvPXu_sBLhyjKwy2y3RMO6Rzh3esvl7-TnoEz5nUz_HVGkFlFAOwVwjgvOZG5nGQ37zMQ_

using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Text;
using System.Windows.Forms;
using System.Net;               // 套接字编程引入这两个命名空间
using System.Net.Sockets;
using System.Threading;
using System.IO;
using Voice;

namespace Server
{
    public partial class Form1 : Form
    {
        private static IPEndPoint ePoint;   //IP+端口号
        private Socket r;                   //声明一个套接字r,用于语音聊天
        TcpListener listener;               //声明一个侦听
        private int i;                      //声明变量i,j
        private int j;
        TcpClient remoteClient;             //声明远程客户端
        private Thread td;                  //声明线程td,t
        private Thread t;                   //用于侦听语音聊天的信息
        private bool connected = false;
        const int BufferSize = 8192;        //分配缓存大小
        private WaveOutPlayer m_Player;
        private WaveInRecorder m_Recorder;
        private byte[] m_PlayBuffer;
        private byte[] m_RecBuffer;
        private FifoStream m_Fifo = new FifoStream();

        public Form1()
        {
            InitializeComponent();
        }

        private void Form1_Load(object sender, EventArgs e)//加载用户界面
        {
            MessageBox.Show(this,"开启服务","提示");
            System.Windows.Forms.Control.CheckForIllegalCrossThreadCalls = false;
            this.ActiveControl = this.txtIP;//光标闪烁
            txtRecord.Text = "【服务器运行中......】";

            t = new Thread(new ThreadStart(Voice_In));//调用方法
        }

        private void btnConfirm_Click(object sender, EventArgs e)
        {
            try
            {
                ePoint = new IPEndPoint(IPAddress.Parse(txtIP.Text), int.Parse("8660"));
                txtRecord.AppendText(Environment.NewLine);
                txtRecord.Text += "【提示:】 IP已确定! ";
                txtRecord.SelectionStart = txtRecord.Text.Length;
                txtRecord.ScrollToCaret();

            }
            catch
            {
                txtRecord.AppendText(Environment.NewLine);
                txtRecord.Text += "【提示:】 请输入有效的IP地址! ";
                txtRecord.SelectionStart = txtRecord.Text.Length;
                txtRecord.ScrollToCaret();
                txtIP.Clear();
            }
        }

        private void btnStart_Click(object sender, EventArgs e)
        {
            createLinked();//调用方法1
            r = new Socket(AddressFamily.InterNetwork, SocketType.Dgram, ProtocolType.Udp);

        }

        public void createLinked()//方法1:建立连接
        {
            try
            {

                listener = new TcpListener(IPAddress.Parse(txtIP.Text), 8660);//实例化一个侦听
            }
            catch
            {
                txtRecord.AppendText(Environment.NewLine);
                txtRecord.Text += "【提示:】 请输入有效的IP地址! ";
                txtRecord.SelectionStart = txtRecord.Text.Length;
                txtRecord.ScrollToCaret();
                i = 3;
            }
            if (i != 3)
            {
                try
                {
                    listener.Start();           // 开始侦听
                    remoteClient = listener.AcceptTcpClient();
                    i = 2;
                    this.txtIP.Enabled = false;
                    this.btnConfirm.Enabled = false;
                    this.btnStart.Enabled = false;
                    td = new Thread(new ThreadStart(this.StartListen));//调用方法2
                    // i = 1;
                    td.Start();
                    // 打印连接到的客户端信息
                    txtRecord.AppendText(Environment.NewLine);
                    txtRecord.Text += "【提示:】 连接已建立! ";
                }
                catch
                {
                    txtRecord.AppendText(Environment.NewLine);
                    txtRecord.Text += "【提示:】 请输入有效的IP地址! ";
                    txtRecord.SelectionStart = txtRecord.Text.Length;
                    txtRecord.ScrollToCaret();
                    txtIP.Clear();
                }
            }
        }

        private void StartListen()//方法2:用于侦听来自客户端的信息
        {
            //tcpListener = listener.AcceptTcpClient() ;
            //tcpListener.Start();
            while (true)
            {
                NetworkStream streamToClient = remoteClient.GetStream();
                byte[] buffer = new byte[BufferSize];
                int bytesRead = streamToClient.Read(buffer, 0, BufferSize);
                //tx(bytesRead.ToString());//转换成字节数输出
                // 获得请求的字符串
                string msg = Encoding.Unicode.GetString(buffer, 0, bytesRead);
                tx(msg);
            }
        }

        private void tx(string s)//方法3 用于改变聊天记录文本框的内容
        {

            txtRecord.AppendText(Environment.NewLine);//向文本框的当前文本追加文本
            txtRecord.Text += "【信息来自客户端: ...】" + s;
            txtRecord.Focus();  //接收到焦点
            txtRecord.Select(txtRecord.Text.Length, 0);//光标移动到文本的末尾,选择字符数为0
            txtRecord.ScrollToCaret();//移动滚动条
            //移动滚动条到最后!
        }

        private void btnSend_Click(object sender, EventArgs e)
        {
            if (i == 2)
            {
                string msg = txtInput.Text;
                NetworkStream streamToClient = remoteClient.GetStream();
                byte[] buffer = Encoding.Unicode.GetBytes(msg);     // 获得缓存
                streamToClient.Write(buffer, 0, buffer.Length);     // 发往客户端
                txtRecord.AppendText(Environment.NewLine);
                txtRecord.Text += "【发送到客户端:】 " + msg;
                txtInput.Clear();
                txtRecord.Focus();  //接收到焦点
                txtRecord.Select(txtRecord.Text.Length, 0);//光标移动到文本的末尾,选择字符数为0
                txtRecord.ScrollToCaret();//移动滚动条
                //移动滚动条到最后!
            }
            else if (i != 3)
            {
                txtRecord.AppendText(Environment.NewLine);
                txtRecord.Text += "【提示:】 尚未连接! ";
                txtRecord.SelectionStart = txtRecord.Text.Length;
                txtRecord.ScrollToCaret();
            }
        }

        private void Voice_In()                 //获取语音输入流
        {
            byte[] br;
            r.Bind(ePoint);

            while (true)
            {
                br = new byte[16384];
                try
                {
                    r.Receive(br);
                }
                catch
                {
                }
                m_Fifo.Write(br, 0, br.Length);
            }
        }

        private void Voice_Out(IntPtr data, int size)//获取语音输入流
        {
            //for Recorder
            if (m_RecBuffer == null || m_RecBuffer.Length < size)
                m_RecBuffer = new byte[size];
            System.Runtime.InteropServices.Marshal.Copy(data, m_RecBuffer, 0, size);
            //Microphone ==> data ==> m_RecBuffer ==> m_Fifo
            r.SendTo(m_RecBuffer, remoteClient.Client.RemoteEndPoint);
        }

        private void Filler(IntPtr data, int size)
        {
            if (m_PlayBuffer == null || m_PlayBuffer.Length < size)
                m_PlayBuffer = new byte[size];
            if (m_Fifo.Length >= size)
                m_Fifo.Read(m_PlayBuffer, 0, size);
            else
                for (int i = 0; i < m_PlayBuffer.Length; i++)
                    m_PlayBuffer[i] = 0;
            System.Runtime.InteropServices.Marshal.Copy(m_PlayBuffer, 0, data, size);
            // m_Fifo ==> m_PlayBuffer==> data ==> Speakers
        }

        private void Start()
        {
            Stop();
            try
            {
                WaveFormat fmt = new WaveFormat(44100, 16, 2);
                m_Player = new WaveOutPlayer(-1, fmt, 16384, 3, new BufferFillEventHandler(Filler));
                m_Recorder = new WaveInRecorder(-1, fmt, 16384, 3, new BufferDoneEventHandler(Voice_Out));
            }
            catch
            {
                Stop();
                throw;
            }
        }

        private void Stop()
        {
            if (m_Player != null)
                try
                {
                    m_Player.Dispose();
                }
                finally
                {
                    m_Player = null;
                }
            if (m_Recorder != null)
                try
                {
                    m_Recorder.Dispose();
                }
                finally
                {
                    m_Recorder = null;
                }
            m_Fifo.Flush();
        }

        private void btnSound_Click(object sender, EventArgs e)
        {
            if (i == 2)
            {
                j = 1;
                if (connected == false)
                {
                    t.Start();
                    connected = true;
                }

                Start();
            }
            else
            {
                txtRecord.AppendText(Environment.NewLine);
                txtRecord.Text += "【提示:】 尚未连接! ";
                txtRecord.SelectionStart = txtRecord.Text.Length;
                txtRecord.ScrollToCaret();
            }
        }

        private void Server_Closing(object sender, FormClosingEventArgs e)
        {
            if (this.listener != null)
            {
                listener.Stop();
            }
            if (td != null)
            {
                if (td.ThreadState == ThreadState.Running)
                {
                    td.Abort();
                }
            }
            if (t != null)
            {
                if (t.ThreadState == ThreadState.Running)
                {
                    t.Abort();
                }
            }
            if (j == 1)
            {
                r.Close();
            }
        }

    }
}

基于C#局域网语音聊天

标签:orm   list   eve   sock   res   app   +=   引入   文本   

原文地址:https://www.cnblogs.com/asdyzh/p/9940783.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!