C#编写的程序如何连接云服务器

C#编写的程序如何连接云服务器,第1张

你了解TCP/IP socket编程相关知识吗?

网页链接

首先你要在云服务器上运行一个服务器程序,然后在本机运行客户端程序,两者通过TCP协议通讯交换数据(即你所说的连上云服务器)。

最简单的服务器程序:

using System;
using SystemIO;
using SystemNet;
using SystemNetSockets;
using SystemText;
class MyTcpListener
{
  public static void Main()
  { 
    TcpListener server=null;   
    try
    {
      // Set the TcpListener on port 13000
      Int32 port = 13000;
      IPAddress localAddr = IPAddressParse("127001");
      
      // TcpListener server = new TcpListener(port);
      server = new TcpListener(localAddr, port);
      // Start listening for client requests
      serverStart();
         
      // Buffer for reading data
      Byte[] bytes = new Byte[256];
      String data = null;
      // Enter the listening loop
      while(true) 
      {
        ConsoleWrite("Waiting for a connection ");
        
        // Perform a blocking call to accept requests
        // You could also user serverAcceptSocket() here
        TcpClient client = serverAcceptTcpClient();            
        ConsoleWriteLine("Connected!");
        data = null;
        // Get a stream object for reading and writing
        NetworkStream stream = clientGetStream();
        int i;
        // Loop to receive all the data sent by the client
        while((i = streamRead(bytes, 0, bytesLength))!=0) 
        {   
          // Translate data bytes to a ASCII string
          data = SystemTextEncodingASCIIGetString(bytes, 0, i);
          ConsoleWriteLine("Received: {0}", data);
       
          // Process the data sent by the client
          data = dataToUpper();
          byte[] msg = SystemTextEncodingASCIIGetBytes(data);
          // Send back a response
          streamWrite(msg, 0, msgLength);
          ConsoleWriteLine("Sent: {0}", data);            
        }
         
        // Shutdown and end connection
        clientClose();
      }
    }
    catch(SocketException e)
    {
      ConsoleWriteLine("SocketException: {0}", e);
    }
    finally
    {
       // Stop listening for new clients
       serverStop();
    }
      
    ConsoleWriteLine("\nHit enter to continue");
    ConsoleRead();
  }   
}

最简单的客户端:

static void Connect(String server, String message) 
{
  try 
  {
    // Create a TcpClient
    // Note, for this client to work you need to have a TcpServer 
    // connected to the same address as specified by the server, port
    // combination
    Int32 port = 13000;
    TcpClient client = new TcpClient(server, port);
    
    // Translate the passed message into ASCII and store it as a Byte array
    Byte[] data = SystemTextEncodingASCIIGetBytes(message);         
    // Get a client stream for reading and writing
    //  Stream stream = clientGetStream();
    
    NetworkStream stream = clientGetStream();
    // Send the message to the connected TcpServer 
    streamWrite(data, 0, dataLength);
    ConsoleWriteLine("Sent: {0}", message);         
    // Receive the TcpServerresponse
    
    // Buffer to store the response bytes
    data = new Byte[256];
    // String to store the response ASCII representation
    String responseData = StringEmpty;
    // Read the first batch of the TcpServer response bytes
    Int32 bytes = streamRead(data, 0, dataLength);
    responseData = SystemTextEncodingASCIIGetString(data, 0, bytes);
    ConsoleWriteLine("Received: {0}", responseData);         
    // Close everything
    streamClose();         
    clientClose();         
  } 
  catch (ArgumentNullException e) 
  {
    ConsoleWriteLine("ArgumentNullException: {0}", e);
  } 
  catch (SocketException e) 
  {
    ConsoleWriteLine("SocketException: {0}", e);
  }
    
  ConsoleWriteLine("\n Press Enter to continue");
  ConsoleRead();
}

TCP指的是传输控制协议。它是一种面向连接导向的、可靠地及基于字节流的运输层通信协议。而在接触TCP中还有UDP,UDP也是一项重要的传输协议。TCP提供超时重发,丢弃重复数据,检验数据,流量控制等功能,保证数据能从一端传到另一端
1、提供IP环境下的数据可靠传输(一台计算机发出的字节流会无差错的发往网络上的其他计算机,而且计算机A接收数据包的时候,也会向计算机B回发数据包,这也会产生部分通信量),有效流控,全双工 *** 作(数据在两个方向上能同时传递),多路复用服务,是面向连接,端到端的传输;
2、面向连接:正式通信前必须要与对方建立连接。事先为所发送的数据开辟出连接好的通道,然后再进行数据发送,就像打电话。
3、TCP支持的应用协议:FTP 文件传送、RLogin 远程登录、SMTP POP3 电子邮件、NFS 网络文件系统、远程打印、远程执行、名字服务器终端服务器等服务类型。

注:为了更好的体验,将内容复制到工具中效果才好

#coturn服务器配置

## *** 作系统:建议使用ubuntu16+

##安装步骤:

以下安装以ubuntu16为例

### 安装软件包

apt update

apt install coturn

### 配置coturn服务器

#### 复制DTLS、TLS支持的证书文件(目录中已经有相应的证书)

cp /usr/share/coturn/examples/etc/turn_server_certpem /etc/turn_server_certpem

cp /usr/share/coturn/examples/etc/turn_server_pkeypem /etc/turn_server_pkeypem

#### 编辑/etc/turnserverconf文件

listening-device=eth0 #网卡

listening-port=3478 #对外服务的商品,需要在防火墙、云服务器安全组放通,协议为UDP/TCP,出入站都需要

listening-ip=127001 #内网地址

tls-listening-port=5349 #备用端口

listening-ip=1721704 #局域网地址

relay-ip=1721704 #局域网地址

external-ip=8101870 #外网地址

lt-cred-mech

server-name=stunxxxcn #域名

realm=stunxxxcn #域名

min-port=50001 #穿透需要用到的开始端口 需要在防火墙,云服务器安全组中放通

max-port=50009 #穿透需要用到的结束端口

user=test:test #用户名:密码 测试或者客户端接入时需要用到

userdb=/var/db/turndb #数据文件的位置,如果没有该文件,启动会有错误提示

cert=/etc/turn_server_certpem #密钥相关 上面步骤准备的

pkey=/etc/turn_server_pkeypem #密钥相关 上面步骤准备的

no-stdout-log

log-file=/var/tmp/turnlog #日志文件

pidfile="/var/run/turnserverpid" #pid文件位置

no-stun #不使用stun服务 主要用于测试turn中继方式时来关闭stun  更多类容可以参考配置文件自带的说明

### 编辑/etc/default/coturn文件

默认是不需要改的,但还是检查一下

TURNSERVER_ENABLED=1

## 安装完成,重启服务

service coturn restart

## 端口放通

参考各系统、服务器,不赘述

## 测试

使用自带工具

turnutils_uclient ip或者域名 -u 用户名 -w 密码

## 客户端使用

iceServers: [{

                'urls': 'stun:stunxxxxcn:3478',

                'credential': "test",

                'username': "test"

            }

            ,{

                'urls': 'turn:stunxxxxcn:3478',

                'credential': "test",

                'username': "test"

            }];

如您云主机有些TCP或UDP端口不能使用,请先确认使用的端口在您开通云主机时是否有申请开通,如之前已申请开通,请检查云主机上的防火墙是否有做相应的规则;如之前没有申请开通该端口,则需要向系统集成中心提交端口开通申请表开通该端口。(上述内容仅适用于广东联通用户)

原则上不需要对云服务器做特别的配置,建议你可以使用小鸟云服务器进行设置。对关联到TCP类型
VIP的Linux云服务器,需要修改系统配置文件/etc/sysctlconf以下三项为0:
netipv4confdefaultrp_filter = 0
netipv4confallrp_filter = 0
netipv4confeth0rp_filter = 0
如果部署在同一内网网段下的云服务器之间有通信需求,且发现有无法通信的情况存在,那么需要检查如下参数的配置是否正确:
netipv4confdefaultarp_announce =2
netipv4confallarp_announce =2
并使用sysctl –p更新配置。


欢迎分享,转载请注明来源:内存溢出

原文地址: https://outofmemory.cn/zz/13476799.html

(0)
打赏 微信扫一扫 微信扫一扫 支付宝扫一扫 支付宝扫一扫
上一篇 2023-08-14
下一篇 2023-08-14

发表评论

登录后才能评论

评论列表(0条)

保存