日期:2014-05-18 浏览次数:20800 次
using System; using System.Text; using System.Net; using System.IO; using System.Web.Security; using System.Net.Sockets; using System.Threading; namespace SocketCilent { /// /// BusSocket 的摘要说明。 /// public class SocketTest { private Socket socket; //获得的Socket private int PORT=9999; //监听的端口 private Thread ThListen; private TcpListener tcp; public void Start() { try { ThListen = new Thread(new ThreadStart(jianting)); ThListen.Start(); } catch { } } public void Stop() { try { tcp.Stop(); ThListen.Abort(); } catch { [b][color=#FF0000]//{"未将对象引用设置到对象的实例。" }一调用这个方法就提示[/color][/b] } } private void jianting() { try { NetworkStream netStream; byte[] GetMsgByte = new byte[1024]; byte[] ReturnMsgByte = new Byte[2]; tcp= new TcpListener(PORT); tcp.Start(); while(true) { socket = tcp.AcceptSocket(); if(socket.Connected) { netStream = new NetworkStream(socket, true); netStream.Read(GetMsgByte, 0, GetMsgByte.Length); netStream.Flush(); netStream.Close(); socket.Close(); } } } catch { [color=#FF0000]//{"通常每个套接字地址(协议/网络地址/端口)只允许使用一次。" }[/color][b][/b] } } }