1.关于异常的处理
代码
try
{
client = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp);
client.Connect(iep);
}
catch
{
Console.WriteLine( " 无法连接服务器! " );
return ;
}
finally
{
// 这里可以写释放资源的代码
}
{
client = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp);
client.Connect(iep);
}
catch
{
Console.WriteLine( " 无法连接服务器! " );
return ;
}
finally
{
// 这里可以写释放资源的代码
}
2.数据缓冲区处理
1)合理缓冲区处理:
代码
while
(server.Connected)
{
try
{
i = server.Receive(bytes);
}
catch
{
break ;
}
if (i != 0 )
{
// 注意这里的i的作用
data = System.Text.Encoding.ASCII.GetString(bytes, 0 , i);
Console.WriteLine( " 收到的数据:{0} " , data);
data = data.ToUpper();
byte [] msg = System.Text.Encoding.ASCII.GetBytes(data);
server.Send(msg);
Console.WriteLine( " 发送的数据:{0} " , data);
}
}
{
try
{
i = server.Receive(bytes);
}
catch
{
break ;
}
if (i != 0 )
{
// 注意这里的i的作用
data = System.Text.Encoding.ASCII.GetString(bytes, 0 , i);
Console.WriteLine( " 收到的数据:{0} " , data);
data = data.ToUpper();
byte [] msg = System.Text.Encoding.ASCII.GetBytes(data);
server.Send(msg);
Console.WriteLine( " 发送的数据:{0} " , data);
}
}
2)不合理的缓冲区后果:
1.缓冲区过大,则会读入非有用信息的数据(空格或上次遗留在缓冲区中的数据)
2.缓冲区过小,则会读入的信息不完整