ClientTest:
using System;
using System.Net.Sockets;
using System.Text;
class TcpClientTest
{
static void Main(string[] args)
{
try
{
// 创建一个TcpClient实例并连接到服务器
TcpClient client = new TcpClient("1vg5062570.51mypc.cn", 43319);
//1vg5062570.51mypc.cn:43319
// 获取一个NetworkStream对象以进行读写
NetworkStream stream = client.GetStream();
// 将消息转换为字节数组
string message = "Hello from the client!";
byte[] data = Encoding.ASCII.GetBytes(message);
// 发送消息到服务器
stream.Write(data, 0, data.Length);
// 读取服务器的响应
byte[] buffer = new byte[4096];
int bytesRead = stream.Read(buffer, 0, buffer.Length);
// 将接收到的字节转换为字符串
string responseData = Encoding.ASCII.GetString(buffer, 0, bytesRead);
Console.WriteLine("Received from server: " + responseData);
// 关闭连接
client.Close();
}
catch (Exception e)
{
Console.WriteLine("Error: " + e.Message);
}
// 等待用户按键,以便在控制台中查看结果
Console.WriteLine("Press Enter to continue...");
Console.ReadLine();
}
}
ClientTestV3:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Net.Sockets;
using System.Text;
using System.Threading.Tasks;
using Newtonsoft.Json;
using System.IO;
public class IPport
{
public string IP { get; set; }
public int Port { get; set; }
}
namespace ClientTestV3
{
internal class Program
{
static void Main(string[] args)
{
try
{
string jsonFilePath = "ipport.json"; // 替换为你的JSON文件路径
// 读取文件内容
string jsonContent = File.ReadAllText(jsonFilePath);
// 反序列化JSON字符串到对象
IPport ipaddr = JsonConvert.DeserializeObject<IPport>(jsonContent);
// 输出结果
Console.WriteLine($"{ipaddr.IP}:{ipaddr.Port}");
// 创建一个TcpClient实例并连接到服务器
TcpClient client = new TcpClient($"{ipaddr.IP}", ipaddr.Port);
// 获取一个NetworkStream对象以进行读写
NetworkStream stream = client.GetStream();
// 将消息转换为字节数组
string message = "Hello from the client!";
Random rand = new Random();
message += rand.Next().ToString();
byte[] data = Encoding.ASCII.GetBytes(message);
// 发送消息到服务器
stream.Write(data, 0, data.Length);
// 读取服务器的响应
byte[] buffer = new byte[4096];
int bytesRead = stream.Read(buffer, 0, buffer.Length);
// 将接收到的字节转换为字符串
string responseData = Encoding.ASCII.GetString(buffer, 0, bytesRead);
Console.WriteLine("Received from server: " + responseData);
Console.WriteLine("ReceivedBytes:{0}", bytesRead);
// 关闭连接
client.Close();
}
catch (Exception e)
{
Console.WriteLine("Error: " + e.Message);
}
// 等待用户按键,以便在控制台中查看结果
Console.WriteLine("Press Enter to continue...");
Console.ReadLine();
}
}
}