日期:2014-05-18 浏览次数:20638 次
try { if(socket.Connected) //判断是否连接 { socket.Send(data); //发送数据 } } catch { socket.Close(); //产生异常,关闭接口。 }
------解决方案--------------------
using System; using System.Net; using System.Net.Sockets; using System.Text; public class SimpleTcpClient { public static void Main() { byte[] data = new byte[1024]; string input, stringData; IPEndPoint ipep = new IPEndPoint( IPAddress.Parse("127.0.0.1"), 9050); Socket server = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp); try { server.Connect(ipep); } catch (SocketException e) { Console.WriteLine("Unable to connect to server."); Console.WriteLine(e.ToString()); return; } int recv = server.Receive(data); stringData = Encoding.ASCII.GetString(data, 0, recv); Console.WriteLine(stringData); while(true) { input = Console.ReadLine(); if (input == "exit") break; server.Send(Encoding.ASCII.GetBytes(input)); data = new byte[1024]; recv = server.Receive(data); stringData = Encoding.ASCII.GetString(data, 0, recv); Console.WriteLine(stringData); } Console.WriteLine("Disconnecting from server..."); server.Shutdown(SocketShutdown.Both); server.Close(); } }
------解决方案--------------------
流来处理发送和接收,mystream.write(data) //发送
mystream.read//接收
在接收的时候这样做
try//捕捉异常,例如与客户端的网络突然被中断。。等等
{
byte []bb=new byte[1024];
int rLen=mystream.read(bb, 0, 1024);
if (rLen!=0)//接收数据正常
{
//做你的处理
}
else//客户端主动断开了连接
{
//既然断开了就做点什么,关闭mystream,停止发送mystream.write(data)
}
}
catch (Exception)
{
//捕捉到异常之后当然也要关闭当前的mystream停止发送mystream.write(data)
//在做点别的。。。-_-!!
}
------解决方案--------------------
哦还漏点东西
1。先判断是否监听到了连接,若已监听到成功连接,则开始发送
既然你用的是stream
和tcplistener
那么应该用的TcpClient=tcplistener.AcceptTcpClient
mystream=TcpClient.GetStream();吧
就按上面他们说的你这样判断
if(TcpClient.Connected)//判断是否连接上了
{
//。。。。。。。。。。里面用一个循环或者线程之类的来控制mystream.read
}
2。当监听到连接关闭时,则停止发送
的判断就按我前面回帖说的判断