关键词搜索

源码搜索 ×
×

C#Socket TCP通信测试&委托传值到控件&DirectSound录音测试源码

发布2017-12-28浏览801次

详情内容

C#里面Socket有异步和同步之分,可参考:https://docs.microsoft.com/en-us/dotnet/framework/network-programming/socket-code-examples进行学习。网络上很多有关DirectSound的Socket声音采集示例,不过都是单独的一个工具类(如:DirectSoundCapture),花了点时间实现了Socket的调用,顺便总结分享一下。下图为测试示例:


Socket客户端

  1. using System;
  2. using System.Collections.Generic;
  3. using System.Linq;
  4. using System.Net;
  5. using System.Net.Sockets;
  6. using System.Text;
  7. using System.Threading.Tasks;
  8. /// <summary>
  9. /// 参考:https://docs.microsoft.com/en-us/dotnet/framework/network-programming/socket-code-examples
  10. /// </summary>
  11. namespace DirectsoundTest
  12. {
  13. class SocketClient
  14. {
  15. /// <summary>
  16. /// 启动客户端socket连接
  17. /// </summary>
  18. public static void StartClient(string data)
  19. {
  20. // Data buffer for incoming data.
  21. byte[] bytes = new byte[1024];
  22. // Connect to a remote device.
  23. try
  24. {
  25. // Establish the remote endpoint for the socket.
  26. // This example uses port 11000 on the local computer.
  27. IPHostEntry ipHostInfo = Dns.GetHostEntry(Dns.GetHostName());
  28. IPAddress ipAddress = ipHostInfo.AddressList[0];
  29. IPEndPoint remoteEP = new IPEndPoint(ipAddress, 11000);
  30. // Create a TCP/IP socket.
  31. Socket sender = new Socket(ipAddress.AddressFamily,SocketType.Stream, ProtocolType.Tcp);
  32. // Connect the socket to the remote endpoint. Catch any errors.
  33. try
  34. {
  35. sender.Connect(remoteEP);
  36. Console.WriteLine("Socket connected to {0}",
  37. sender.RemoteEndPoint.ToString());
  38. // Encode the data string into a byte array.
  39. byte[] msg = Encoding.UTF8.GetBytes(data+"<EOF>");
  40. // Send the data through the socket.
  41. int bytesSent = sender.Send(msg);
  42. // Receive the response from the remote device.
  43. int bytesRec = sender.Receive(bytes);
  44. Console.WriteLine("Echoed test = {0}",
  45. Encoding.UTF8.GetString(bytes, 0, bytesRec));
  46. // Release the socket.
  47. sender.Shutdown(SocketShutdown.Both);
  48. sender.Close();
  49. }
  50. catch (ArgumentNullException ane)
  51. {
  52. Console.WriteLine("ArgumentNullException : {0}", ane.ToString());
  53. }
  54. catch (SocketException se)
  55. {
  56. Console.WriteLine("SocketException : {0}", se.ToString());
  57. }
  58. catch (Exception e)
  59. {
  60. Console.WriteLine("Unexpected exception : {0}", e.ToString());
  61. }
  62. }
  63. catch (Exception e)
  64. {
  65. Console.WriteLine(e.ToString());
  66. }
  67. }
  68. }
  69. }


Socket服务端

  1. using System;
  2. using System.Collections.Generic;
  3. using System.Linq;
  4. using System.Net;
  5. using System.Net.Sockets;
  6. using System.Text;
  7. using System.Threading.Tasks;
  8. /// <summary>
  9. /// 参考:https://docs.microsoft.com/en-us/dotnet/framework/network-programming/socket-code-examples
  10. /// </summary>
  11. namespace DirectsoundTest
  12. {
  13. class SocketServer
  14. {
  15. // Incoming data from the client.
  16. public static string data = null;
  17. /// <summary>
  18. /// 启动服务端socket监听
  19. /// </summary>
  20. public static void StartListening()
  21. {
  22. // Data buffer for incoming data.
  23. byte[] bytes = new Byte[1024];
  24. // Establish the local endpoint for the socket.
  25. // Dns.GetHostName returns the name of the
  26. // host running the application.
  27. IPHostEntry ipHostInfo = Dns.GetHostEntry(Dns.GetHostName());
  28. IPAddress ipAddress = ipHostInfo.AddressList[0];
  29. IPEndPoint localEndPoint = new IPEndPoint(ipAddress, 11000);
  30. // Create a TCP/IP socket.
  31. Socket listener = new Socket(ipAddress.AddressFamily,SocketType.Stream, ProtocolType.Tcp);
  32. // Bind the socket to the local endpoint and
  33. // listen for incoming connections.
  34. try
  35. {
  36. listener.Bind(localEndPoint);
  37. listener.Listen(10);
  38. // Start listening for connections.
  39. while (true)
  40. {
  41. Console.WriteLine("Waiting for a connection...");
  42. // Program is suspended while waiting for an incoming connection.
  43. Socket handler = listener.Accept();
  44. data = null;
  45. // An incoming connection needs to be processed.
  46. while (true)
  47. {
  48. bytes = new byte[1024];
  49. int bytesRec = handler.Receive(bytes);
  50. data += Encoding.UTF8.GetString(bytes, 0, bytesRec);
  51. if (data.IndexOf("<EOF>") > -1)
  52. {
  53. break;
  54. }
  55. }
  56. // Show the data on the console.
  57. Console.WriteLine("Text received : {0}", data);
  58. // Echo the data back to the client.
  59. byte[] msg = Encoding.UTF8.GetBytes(data);
  60. handler.Send(msg);
  61. handler.Shutdown(SocketShutdown.Both);
  62. handler.Close();
  63. }
  64. }
  65. catch (Exception e)
  66. {
  67. Console.WriteLine(e.ToString());
  68. }
  69. Console.WriteLine("\nPress ENTER to continue...");
  70. Console.Read();
  71. }
  72. }
  73. }


窗体&委托传值

  1. using System;
  2. using System.Collections.Generic;
  3. using System.ComponentModel;
  4. using System.Data;
  5. using System.Drawing;
  6. using System.Linq;
  7. using System.Text;
  8. using System.Threading;
  9. using System.Threading.Tasks;
  10. using System.Windows.Forms;
  11. namespace DirectsoundTest
  12. {
  13.     public partial class FrmSocket : Form
  14.     {
  15.         public FrmSocket()
  16.         {
  17.             InitializeComponent();
  18.         }
  19.         /// <summary>
  20.         /// 启动服务端socket连接
  21.         /// </summary>
  22.         /// <param name="sender"></param>
  23.         /// <param name="e"></param>
  24.         private void btnBindSocketServer_Click(object sender, EventArgs e)
  25.         {
  26.             btnBindSocketServer.Enabled = false;
  27.             Thread thread = new Thread(() => {
  28.                 SocketServer.StartListening();
  29.             });
  30.             thread.IsBackground = true;
  31.             thread.Start();
  32.         }
  33.         // 委托设置值
  34.         delegate void setDataToListView(string data);
  35.         private void SetListViewData(string data)
  36.         {
  37.             if (this.listViewData.InvokeRequired)
  38.             {
  39.                 setDataToListView stcb = new setDataToListView(SetListViewData);
  40.                 this.Invoke(stcb, new object[] { data });
  41.             }
  42.             else
  43.             {
  44.                 this.listViewData.Items.Add(data);
  45.             }
  46.         }
  47.         /// <summary>
  48.         /// 客户端发送socket连接数据
  49.         /// </summary>
  50.         /// <param name="sender"></param>
  51.         /// <param name="e"></param>
  52.         private void btnSocketClient_Click(object sender, EventArgs e)
  53.         {
  54.             // 发送UTF8文字
  55.             byte[] buffer = Encoding.UTF8.GetBytes(this.textBox.Text.ToString());
  56.             string data = Encoding.UTF8.GetString(buffer);
  57.             Thread thread = new Thread(() => {
  58.                 SocketClient.StartClient(data);
  59.                 SetListViewData(data);//委托设置控件的值
  60.             });
  61.             thread.IsBackground = true;
  62.             thread.Start();
  63.         }
  64.         /// <summary>
  65.         /// 打开服务端
  66.         /// </summary>
  67.         /// <param name="sender"></param>
  68.         /// <param name="e"></param>
  69.         private void toolStripMenuItemServer_Click(object sender, EventArgs e)
  70.         {
  71.             if (!Setting.SERVER_BINDED)
  72.             {
  73.                 FrmServer frmServer = new FrmServer();
  74.                 frmServer.Show();
  75.                 Setting.SERVER_BINDED = true;
  76.             }
  77.             else {
  78.                 MessageBox.Show("服务端已注册");
  79.             }
  80.         }
  81.         /// <summary>
  82.         /// 打开客户端
  83.         /// </summary>
  84.         /// <param name="sender"></param>
  85.         /// <param name="e"></param>
  86.         private void toolStripMenuItemClient_Click(object sender, EventArgs e)
  87.         {
  88.             FrmClient frmClient = new FrmClient();
  89.             frmClient.Show();
  90.         }
  91.     }
  92. }

委托写法-实现跨线程修改ListView控件值:

  1. // 委托设置值
  2. delegate void setDataToListView(string data);
  3. private void SetListViewData(string data)
  4. {
  5. if (this.listViewData.InvokeRequired)
  6. {
  7. setDataToListView stcb = new setDataToListView(SetListViewData);
  8. this.Invoke(stcb, new object[] { data });
  9. }
  10. else
  11. {
  12. this.listViewData.Items.Add(data);
  13. }
  14. }

DirectSound录音测试源码

Socket例子和DirectSound录音代码都在Github上可以找到。

Github地址:https://github.com/BoonyaCSharp-ASP/DirectSoundTest


相关技术文章

点击QQ咨询
开通会员
返回顶部
×
微信扫码支付
微信扫码支付
确定支付下载
请使用微信描二维码支付
×

提示信息

×

选择支付方式

  • 微信支付
  • 支付宝付款
确定支付下载