本文实例为大家分享了C#以流方式读socket超时设置的具体代码,供大家参考,具体内容如下

using System;
using System.IO;
using System.Net;
using System.Text;
using System.Net.Sockets;
public class client
{
public static void Main()
{
try
{
// 新建客户端套接字
TcpClient tcpclnt = new TcpClient();
Console.WriteLine("连接.....");
// 连接服务器
tcpclnt.ReceiveTimeout = 3000;//设置Socket的接收超时时间为3S。
tcpclnt.Connect("127.0.0.1",8001);
Console.WriteLine("已连接");
Console.Write("请输入要传输的字符串 : ");
// 读入字符串
String str=Console.ReadLine();
// 得到客户端的流
Stream stm = tcpclnt.GetStream();
// 发送字符串
ASCIIEncoding asen= new ASCIIEncoding();
byte[] ba=asen.GetBytes(str);
Console.WriteLine("传输中.....");
stm.Write(ba,0,ba.Length);
// 接收从服务器返回的信息
byte[] bb=new byte[100];
int k=stm.Read(bb,0,100); //3秒后会出现超时异常
// 输出服务器返回信息
for (int i=0;i
{
Console.Write(Convert.ToChar(bb[i]));
}
// 关闭客户端连接
tcpclnt.Close();
}
catch (Exception e)
{
Console.WriteLine("Error..... " + e.StackTrace);
}
}
}
另外有需要云服务器可以了解下创新互联scvps.cn,海内外云服务器15元起步,三天无理由+7*72小时售后在线,公司持有idc许可证,提供“云服务器、裸金属服务器、高防服务器、香港服务器、美国服务器、虚拟主机、免备案服务器”等云主机租用服务以及企业上云的综合解决方案,具有“安全稳定、简单易用、服务可用性高、性价比高”等特点与优势,专为企业上云打造定制,能够满足用户丰富、多元化的应用场景需求。