zoukankan      html  css  js  c++  java
  • C# TCP/IP 初探

    /*以下内容来自:http://www.luyikk.com/topic-11961.aspx
    仅用于学习研究*/

    很久以前就一直想玩P2P做一些商用的应用软件

    早前没有C#,或者.NET的时候,我可以用VB6 采用 winsock来开发一些应用软件.

    距离VB6那个时候已经有近 5年没有玩过了.

    这几日开了VS2005来玩C#. 翻无数贴子,均不能成功实现C S 之间的通讯.

    不是死机,就是到处有错.

    经过俺几天几夜不眠不休的认真研究,最终研究得成正果,小小的爽了一把.

    为了俺们大中华民族的未来软件产业的发展壮大,俺不敢私藏心得体会,

    特此奉献如下, 有钱的打发几个小钱,没钱的捧个人场哈.大牛和大虾就当看猴戏撒.

    废话少说,开场喽

    ---------------------------------------------------------------------------------------------------------------------------

    我是独立二个项目来研究CS端,命名为Server 和 Client

    如下图乱放:

     上面这个图是S端的鸟样

    这个是C端界面

    //下面是代码部分:

    -------------------------------------------------------------------------------------------------------------------

    //client:

    using System;
    using System.Collections.Generic;
    using System.ComponentModel;
    using System.Data;
    using System.Drawing;
    using System.Text;
    using System.Windows.Forms;
    using System.IO;
    using System.Net.Sockets;
    using System.Threading;

    namespace Client
    {
        
    public partial class Form1 : Form
        
    {
            
    //发送消息程序
            public Form1()
            
    {
                InitializeComponent();
            }


            
    private void button1_Click(object sender, EventArgs e)
            
    {
                String mystr 
    = textBox1.Text;

               
    this.sendmymsg();
            
            }

            
    public void sendmymsg()
            
    {
                
    try
                
    {
                    TcpClient client 
    = new TcpClient("127.0.0.1"5567);
                    NetworkStream sendStream 
    = client.GetStream();
                    
    //StreamWriter writer = new StreamWriter(sendStream);
                    String msg = textBox1.Text;
                    Byte[] sendBytes 
    = Encoding.Default.GetBytes(msg);
                    sendStream.Write(sendBytes, 
    0, sendBytes.Length);
                    
    //writer.Flush();
                    sendStream.Close();
                    client.Close();
                    textBox1.Text 
    = "Msg Sent!";

                }

                
    catch(System.Exception e)
                
    {
                    textBox2.Text 
    = e.ToString(); ;

                }

            }


            
    private void textBox1_TextChanged(object sender, EventArgs e)
            
    {

            }

        }

    }


    //Server 部分比较复杂,也列出来,一会拿出来扯

    //Server:

    using System;
    using System.Collections.Generic;
    using System.ComponentModel;
    using System.Data;
    using System.Drawing;
    using System.Text;
    using System.Windows.Forms;
    using System.IO;
    using System.Net.Sockets;
    using System.Threading;
    using System.Net;

    namespace Server
    {
        
    public partial class Form1 : Form
        
    {
            
    //变量
            private ThreadStart start;
            
    private Thread listenThread;
            
    static private bool m_bListening = false;
            
    static private System.Net.IPAddress MyIP = System.Net.IPAddress.Parse("127.0.0.1");
            
    static private TcpListener listener = new TcpListener(MyIP, 5567);
            
    private String msg;
            
    //初始化监听器
            public Form1()
            
    {
                InitializeComponent();
                Control.CheckForIllegalCrossThreadCalls 
    = false;
                start 
    = new ThreadStart(startListen);
                listenThread 
    = new Thread(start);   
            }


            
    private void listBox1_SelectedIndexChanged(object sender, EventArgs e)
            
    {

            }


            
    private void Form1_Load(object sender, EventArgs e)
            
    {
            

            }


            
    private void button1_Click(object sender, EventArgs e)
            
    {
                
    if (m_bListening)
                
    {
                    m_bListening 
    = false;
                    label4.Text 
    = "Server Idle";
                }

                
    else
                
    {
                    m_bListening 
    = true;
                    listenThread.Start();
                    label4.Text 
    = "Server Listening";
                }

               

            }

            
    private void showmore()
            
    {
                textBox1.Text 
    = msg;
            }

            
    private void startListen()
            
    {
                
    //textBox1.Text = "listening";
                listener.Start();
                
    //接收数据
                while (m_bListening)
                
    {
                    
    //测试是否有数据
                    try
                    
    {
                        TcpClient client 
    = listener.AcceptTcpClient();
                        NetworkStream ns 
    = client.GetStream();
                        
    //StreamReader sr = new StreamReader(ns);//流读写器
                        
    //字组处理
                        byte[] bytes = new byte[1024];
                        
    int bytesread = ns.Read(bytes, 0, bytes.Length);
                        msg 
    = Encoding.Default.GetString(bytes, 0, bytesread);
                        
    //显示
                        
    //MessageBox.Show(msg);
                        showmore();
                        ns.Close();
                        client.Close();
                        
    //清场

                    }

                    
    catch (Exception re)
                    
    {
                        MessageBox.Show(re.Message);
                    }


                }

                listener.Stop();
                
    //
            }


        }

    }




    代码部分完成了.

    现在开始口水了,主要对Server 端进行胡扯,C端没有什么好说的,非常的简单明了.S端涉及到多线程,界面线程管理.现在说几点要注意的

    1:中文乱码, 大家别抄书上的代码,用Encoding.ASCII 是不对的,最好用Encoding.Default

    2:如果你的程序没有响应,半死状态,那是因为程序运行到listener.AcceptTcpClient();的时候一直在等待C端的数据.阻塞住了,有人说,会这个状态才是最正常的,此话不错. 所以碰到这个问题,不要相信垃圾书啦. 采用多线程

    3:线程在form1的时候要装载即

            public Form1()
            {
                InitializeComponent();
                Control.CheckForIllegalCrossThreadCalls = false;
                start = new ThreadStart(startListen);
                listenThread = new Thread(start);  
            }

    Control.CheckForIllegalCrossThreadCalls 这一行是为了可以在线程里直接控制S上面的TEXTBOX控件

    如果不用这一行,会报"线程间错误"

    startListen 是有消息的时候,线程调用的子程序.

    就这几个要注意的. 希望大家可以一步调试成功,不要走太多的冤枉路.

    启动 server.exe  和 client.exe  从C发送消息,S端会显示收到的消息.

    表示成功.

    只要这CS能正常通讯,那么其他的你想干什么就干什么了.不用我说了吧?哈哈!

  • 相关阅读:
    python第一个项目:爬取一个网站的所有图片
    python学习笔记(3)
    python学习笔记(3)
    python学习笔记(2)
    python学习笔记(2)
    机器学习入门(1)
    centos7安装google-chrome
    linux 系统监控命令之 top-(转自 Howie的专栏)
    linux 磁盘管理命令之df-(转自 Howie的专栏)
    sizeof()用法汇总-(转自风雷)
  • 原文地址:https://www.cnblogs.com/yiki/p/989993.html
Copyright © 2011-2022 走看看