C#中Socket通讯(外网通讯,借助花生壳内网穿透)

下面是个简单的例子,实现客户端和服务器在外网情况下通讯

建立通讯过程:

1.下载花生壳,开通内网穿透功能(体验版6元),它会分配一个公网ip和一个端口号,如下图

2.利用花生壳将存在服务器程序机器的内网映射至外网,如下图

3.服务器启动程序,ip为内网,端口为花生壳分配的公网端口。

4.客户端去连接公网ip,端口为公网端口

C#测试代码如下:

服务器:

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

namespace Csharp_socket编程_TCP协议
{
  class Program
  {
    private static byte[] result = new byte[1024];
    private static int myProt = 38688; //端口
    static Socket serverSocket;
    static void Main(string[] args)
    {
      //服务器IP地址
      IPAddress ip = IPAddress.Parse("192.168.10.85");
      serverSocket = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp);
      serverSocket.Bind(new IPEndPoint(ip, myProt)); //绑定IP地址:端口
      serverSocket.Listen(10); //设定最多10个排队连接请求
      Console.WriteLine("启动监听{0}成功", serverSocket.LocalEndPoint.ToString());
      //通过Clientsoket发送数据
      Thread myThread = new Thread(ListenClientConnect);
      myThread.Start();
      Console.ReadLine();
    }

    /// <summary>
    /// 监听客户端连接
    /// </summary>
    private static void ListenClientConnect()
    {
      while (true)
      {
        Socket clientSocket = serverSocket.Accept();
        clientSocket.Send(Encoding.ASCII.GetBytes("Server Say Hello"));
        Thread receiveThread = new Thread(ReceiveMessage);
        receiveThread.Start(clientSocket);
      }
    }

    /// <summary>
    /// 接收消息
    /// </summary>
    /// <param name="clientSocket"></param>
    private static void ReceiveMessage(object clientSocket)
    {
      Socket myClientSocket = (Socket)clientSocket;
      while (true)
      {
        try
        {
          //通过clientSocket接收数据
          int receiveNumber = myClientSocket.Receive(result);
          Console.WriteLine("接收客户端{0}消息{1}", myClientSocket.RemoteEndPoint.ToString(), Encoding.ASCII.GetString(result, 0, receiveNumber));
        }
        catch (Exception ex)
        {
          Console.WriteLine(ex.Message);
          myClientSocket.Shutdown(SocketShutdown.Both);
          myClientSocket.Close();
          break;
        }
      }
    }
  }
}

客户端:

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

namespace Csharp_socket编程_TCP协议_客户端
{
  class Program
  {
    private static byte[] result = new byte[1024];
    static void Main(string[] args)
    {
      //设定服务器IP地址
      IPAddress ip = IPAddress.Parse("103.46.128.45");
      Socket clientSocket = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp);
      try
      {
        clientSocket.Connect(new IPEndPoint(ip, 38688)); //配置服务器IP与端口
        Console.WriteLine("连接服务器成功");
      }
      catch
      {
        Console.WriteLine("连接服务器失败,请按回车键退出!");
        return;
      }
      //通过clientSocket接收数据
      int receiveLength = clientSocket.Receive(result);
      Console.WriteLine("接收服务器消息:{0}", Encoding.ASCII.GetString(result, 0, receiveLength));
      //通过 clientSocket 发送数据
      try
      {
        Thread.Sleep(1000); //等待1秒钟
        string sendMessage = "client send Message Hellp" + DateTime.Now;
        clientSocket.Send(Encoding.ASCII.GetBytes(sendMessage));
        Console.WriteLine("向服务器发送消息:{0}" + sendMessage);
      }
      catch
      {
        clientSocket.Shutdown(SocketShutdown.Both);
        clientSocket.Close();
      }

      Console.WriteLine("发送完毕,按回车键退出");
      Console.ReadLine();
    }
  }
}

评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值