📄 echoclienttcp.cs
字号:
using System;
using System.IO;
using System.Text;
using System.Net;
using System.Net.Sockets;
class EchoClientTcp
{
public static void Main(String[] args)
{
//声明欲放置网络传输流对象的变量
NetworkStream NetStream = null;
//从命令行读取Echo服务器的IP地址并产生一个IPAddress对象
IPAddress HostAddr = IPAddress.Parse(args[0]);
//根据IP地址及通信端口7产生一IPEndPoint对象
IPEndPoint host = new IPEndPoint(HostAddr,7);
//产生一相对于本地端IP地址的IPAddress对象
IPAddress LocalAddr = IPAddress.Parse("127.0.0.1");
//根据IP地址及通信端口号13产生一IPEndPoint对象
IPEndPoint local = new IPEndPoint(LocalAddr,13);
//产生TcpClient对象
TcpClient client = new TcpClient(local);
//设置打开延迟关闭连接选项,时间为3秒
client.LingerState = new LingerOption(true,3);
try
{
//连接到所指定的服务器
client.Connect(host);
}
catch(SocketException se)
{
//若无法创建连接则显示出错误信息并退出程序
Console.WriteLine("Could not establish connection to echo server!!");
return;
}
//显示出成功连接的信息
Console.WriteLine("Successfully establish connection to echo server!!");
//向TcpClient对象获取网络传输流
NetStream = client.GetStream();
String tmpstr = "";
while(true)
{
//从命令行读取用户所输入的字符串
tmpstr = Console.ReadLine();
//若用户输入exit则退出循环
if (tmpstr.Equals("exit"))
break;
//将用户所输入的字符串转换为Byte数组以便发送
Byte[] SendBytes = Encoding.ASCII.GetBytes(tmpstr.ToCharArray());
try
{
//把数据发送给Echo服务器
NetStream.Write(SendBytes,0,SendBytes.Length);
}
catch(IOException ioe)
{
Console.WriteLine("Data write error!!");
continue;
}
int bytes = 0;
//声明一个Byte数组,稍后用来存放所接收到的数据
Byte[] RecvBytes = new byte[256];
String RecvString = "";
try
{
//从网络传输流中读取数据,并存放在RecvBytes数组中
bytes = NetStream.Read(RecvBytes,0,RecvBytes.Length);
}
catch(IOException ioe)
{
Console.WriteLine("Data Read error!!");
continue;
}
//将Byte类型的数组转换为字符串
RecvString = Encoding.ASCII.GetString(RecvBytes,0,bytes);
//显示出所接收的数据
Console.WriteLine(RecvString);
}
//关闭网络传输流
NetStream.Close();
//关闭与Echo服务器的连接
client.Close();
}
}
⌨️ 快捷键说明
复制代码
Ctrl + C
搜索代码
Ctrl + F
全屏模式
F11
切换主题
Ctrl + Shift + D
显示快捷键
?
增大字号
Ctrl + =
减小字号
Ctrl + -