当前位置: 代码迷 >> ASP.NET >> TCP/ip Socket 短连接 Demo(生手请进~欢迎拍砖)
  详细解决方案

TCP/ip Socket 短连接 Demo(生手请进~欢迎拍砖)

热度:8998   发布时间:2013-02-25 00:00:00.0
TCP/ip Socket 短连接 Demo(新手请进~~~~欢迎拍砖)
最近实在闲的蛋疼。。。看了下tcp/ip 通信 搞了几个Demo 献给新手(本人也很菜哈。。都是写的短连接,本来tcp的时候想用长连接的 但看了下 头晕中 要搞心跳包 实在能力有限) 不多说 贴图。帖demo
----IP Service ------


----IP Client------


----IP Service Major code------
C# code
 private void BeginListen()        {            serverIP = IPAddress.Parse(tbxIP.Text);            serverFullAddr = new IPEndPoint(serverIP, int.Parse(tbxPort.Text));//设置IP,端口            sock = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp);            //指定本地主机地址和端口号            sock.Bind(serverFullAddr);            lbxMessage.Invoke(new SetTextCallback(SetText), "启动成功 时间:"+DateTime.Now, 1);            byte[] message = new byte[1024];            string mess = "";            while (true)            {                try                {                    sock.Listen(5);//设置监听频率                    Socket newSocket = sock.Accept();//阻塞方式                    int bytes=  newSocket.Receive(message);//接收数据                    mess = Encoding.Default.GetString(message, 0, bytes);//对接收字节编码(S与C 两端编码格式必须一致不然中文乱码)(当接收的字节大于1024的时候 这应该是循环接收,测试就没有那样写了)                    //do                    //{                    //    bytes = newSocket.Receive(message, message.Length, 0);                    //    mess = mess + Encoding.ASCII.GetString(message, 0, bytes);                    //}                   // while (bytes > 0);                    lbxMessage.Invoke(new SetTextCallback(SetText),mess,1);//子线程操作主线程UI控件                    mess = "已接收数据: " + mess + " 当前时间为:" + DateTime.Now;                    newSocket.Send(Encoding.Default.GetBytes(mess));//想客户端发送数据                }                catch (SocketException se)                {                    lbxMessage.Invoke(new SetTextCallback(SetText), mess, 1);                }            }        }


----IP Clinet Major code------
C# code
  //发送消息        private void btnSend_Click(object sender, EventArgs e)        {            serverFullAddr = new IPEndPoint(serverIP, int.Parse(tbxPort.Text));//设置IP,端口            sock = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp);            //指定本地主机地址和端口号            sock.Connect(serverFullAddr);            byte[] byteSend = System.Text.Encoding.Default.GetBytes(this.tbxMessage.Text);            byte[] message = new byte[1024];            string mess = "";            int bytes = 0;            try            {                //发送数据                sock.Send(byteSend);                               bytes = sock.Receive(message);//接收数据                mess = mess + Encoding.Default.GetString(message,0,bytes);//编码(当接收的字节大于1024的时候 这应该是循环接收,测试就没有那样写了)                //do                //{                //    bytes = newSocket.Receive(message, message.Length, 0);                //    mess = mess + Encoding.ASCII.GetString(message, 0, bytes);                //}                // while (bytes > 0);                tbxMessage.Text = mess;             }            catch (Exception ex)            {                lblError.Text = "出现错误,请联系管理员";            }            sock.Close();        }

-----------------------------TCP Demo---------------------------------------

----TCP Service ------


----TCP Client------


----TCP Service code ------
C# code
  static void Main(string[] args)        {            TcpListener listener = null;            int portNum = 9001;            byte[] bytes = new byte[1024];            try            {                Console.WriteLine("开启服务器端窗口。。。。");                Console.WriteLine("请等待连接...");                bool done = false;                listener = new TcpListener(IPAddress.Parse("127.0.0.1"), portNum);                listener.Start();//开始监听                while (!done)                {                    TcpClient client = listener.AcceptTcpClient();                    Console.WriteLine("连接成功........");                    NetworkStream ns = client.GetStream();                    int num=ns.Read(bytes,0,bytes.Length);//读C端发送的数据                    Console.WriteLine(Encoding.ASCII.GetString(bytes, 0, num));//编码                    byte[] byteTime = Encoding.ASCII.GetBytes(DateTime.Now.ToString());                    try                    {                        ns.Write(byteTime, 0, byteTime.Length);//像C端发送数据                        ns.Close();                        client.Close();                    }                    catch (Exception e)                    {                        Console.WriteLine(e.ToString());                    }                }                listener.Stop();            }            catch (Exception ee)            {                Console.Write("错误提示:" + ee.Message);            }            finally            {                // Stop listening for new clients.                listener.Stop();            }            Console.WriteLine("\nHit enter to continue...");            Console.Read();        }
  相关解决方案