单客户端与服务器通信

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

namespace 异步服务器
{
    public partial class Form1 : Form
    {
        public Form1()
        {
            InitializeComponent();         
            this.skinEngine1.SkinFile = Application.StartupPath + "//GlassOrange.ssk";
        }
        public ArrayList array = new ArrayList();
        string PATH=null;
        static int j = 0,k=0;
        ArrayList friends = new ArrayList();
        TcpListener listener1;
        bool IsStart = false;
        delegate void AppendDelegate(string str);
        AppendDelegate Appendstring;
        delegate void AddDelegate(MyFriend frd);
        AddDelegate Addfriend;
        delegate void RemoveDelegate(MyFriend frd);
        RemoveDelegate Removefriend;
        private void AppendMethod(string str)
        {
            if (richTextBox1.Text != null)
            {
                btnClear_Click(btnClear, null);
            }
            richTextBox1.Text=str;
            if (str!= null)
            {
                string a = str.Substring(0, 1);
                switch (a)         //不同的机器,存到不同的文件路径下
                {
                    case "A": 
                       PATH = @"c:\\recive_data.txt";
                       break;
                    case "B":
                       PATH = @"c:\\recive1_data.txt";
                        break;
                }
                //listBox1.SelectedIndex = listBox1.Items.Count - 1;
                //listBox1.ClearSelected();
                StreamWriter sw = new StreamWriter(PATH, true, Encoding.Default);
                //Write a line of text
                sw.WriteLine(str);
                //Write a second line of text
                //Close the file
                sw.Close();

            }
        }
      //不一样 4. private void AddStop(string str)
       // {
          //  richTextBox1.AppendText(str);
        //}
        private void AddMethod(MyFriend frd)
        {
            lock (friends)
            {
                friends.Add(frd);
            }
            comboBox1.Items.Add(frd.socket.RemoteEndPoint.ToString());
        }
        private void RemoveMethod(MyFriend frd)
        {
            int i = friends.IndexOf(frd);
            comboBox1.Items.Remove(i);
            //array.RemoveAt(array.Count - 1);
            lock (friends)
            { friends.Remove(frd); }
            frd.Dispose();
        }


        private void Form1_Load(object sender, EventArgs e)
        {
            Appendstring = new AppendDelegate(AppendMethod);            
            Addfriend = new AddDelegate(AddMethod);
            Removefriend = new RemoveDelegate(RemoveMethod);
            if (!System.IO.Directory.Exists(@"./log"))
                System.IO.Directory.CreateDirectory(@"./log");
        }

        private void btnStart_Click(object sender, EventArgs e)
        {
            if (IsStart) return;
           // IPEndPoint localep = new IPEndPoint(Dns.GetHostAddresses(Dns.GetHostName())[0], 10000);  //保存本机的IP和端口号10000
            IPEndPoint localep = new IPEndPoint( IPAddress.Parse("125.223.113.80"),10000);
            listener1 = new TcpListener(localep);    //TCP服务器2
            listener1.Start(10);
            IsStart = true;
            //richTextBox1.Invoke(Appendstop, string.Format("服务器已启动监听!端点为:{0}"), listener.LocalEndpoint.ToString());
            AsyncCallback callback = new AsyncCallback(AcceptCallback);
            listener1.BeginAcceptSocket(callback, listener1);
            this.btnStart.Enabled = false;
        }
        private void AcceptCallback(IAsyncResult ar)
        {
            try
            {
                Socket handle = listener1.EndAcceptSocket(ar);
                MyFriend frd = new MyFriend(handle);
               comboBox1.Invoke(Addfriend, frd);
               //array.Add(frd);
                AsyncCallback callback;
                if (IsStart)
                {
                    callback = new AsyncCallback(AcceptCallback);
                    listener1.BeginAcceptSocket(callback, listener1);
                }
                frd.ClearBuffer();
                callback = new AsyncCallback(receivecallback);
                frd.socket.BeginReceive(frd.Rcvbuffer, 0, frd.Rcvbuffer.Length, SocketFlags.None, callback, frd);
            }
            catch (Exception e)
            {
                //richTextBox1.Invoke(Appendstring, e);
                IsStart = false;
            }
        }
        private void receivecallback(IAsyncResult ar)
        {
            MyFriend frd = (MyFriend)ar.AsyncState;
            try
            {
                int i = frd.socket.EndReceive(ar);                
                if (i == 0)
                {
                    comboBox1.Invoke(Removefriend, frd);
                    return;
                }//"From[{0}]:{1}", frd.socket.RemoteEndPoint.ToString(),
                else
                {
                    string data = Encoding.UTF8.GetString(frd.Rcvbuffer, 0, i);
                    data = string.Format(data);
                    richTextBox1.Invoke(Appendstring, data);
                    frd.ClearBuffer();
                    AsyncCallback callback = new AsyncCallback(receivecallback);
                    frd.socket.BeginReceive(frd.Rcvbuffer, 0, frd.Rcvbuffer.Length, SocketFlags.None, callback, frd);
                }
            }
            catch
            {
                comboBox1.Invoke(Removefriend, frd);
            }
        }
        private void senddata(MyFriend frd, string data)
        {
            try
            {
                byte[] msg = Encoding.UTF8.GetBytes(data);
                AsyncCallback callback = new AsyncCallback(Sencallback);
                frd.socket.BeginSend(msg, 0, msg.Length, SocketFlags.None, callback, frd);
                data = string.Format("To[{0}]:{1}", frd.socket.RemoteEndPoint.ToString(), data);                
               // richTextBox1.Invoke(Appendstring, data);              
               // richTextBox2.Text = "";
            }
            catch
            {
                comboBox1.Invoke(Removefriend, frd);
            }
        }
        private void Sencallback(IAsyncResult ar)
        {
            MyFriend frd = (MyFriend)ar.AsyncState;
            try
            {
                frd.socket.EndSend(ar);
            }
            catch
            {
                comboBox1.Invoke(Removefriend, frd);
            }
        }

        private void btnStop_Click(object sender, EventArgs e)
        {
            try
            {
                if (!IsStart) return;
                listener1.Stop(); 
                IsStart = false;               
                //服务器已启动监听
                comboBox1.Items.Clear();
                this.btnStart.Enabled = true;
                listener1.Stop();             
            }
            catch (Exception e2)
            {
                MessageBox.Show(e2.Message);
            }
        }             

        private void btnSendMess_Click(object sender, EventArgs e)
        {            
            if (richTextBox2.Text.Trim() == "")
            {
                richTextBox1.AppendText("不能发送空字符");
                richTextBox2.Focus();
                return;
            }
           //if (comboBox1.SelectedIndex < 0)
            {
             //   richTextBox1.AppendText("请在列表中选择发送对象");
              //  return;
            }
            int i = comboBox1.SelectedIndex;//通过选中选项来改变索引值,进而建立起服务器与客户端的通道
            for (int j = 0; j < friends.Count;j++ )   //这个j是要发送的机器的个数,即连上的客户端个数,但是多个客户端没有编
                senddata((MyFriend)friends[j], richTextBox2.Text.Trim());
            richTextBox2.Clear();
           //senddata是发送数据的函数,(MyFriend)friends[i]选中要通信的服务器与客户端的socket
        }

        private void btnClear_Click(object sender, EventArgs e)
        {
            this.richTextBox1.Clear();           
        } 

        
        string fileName = "";//保存日志的路径。文件名为创建时刻的.txt文件    
      
        
        #region 监控变化事件
        string str1 = "WATCH1:" + System.DateTime.Now.ToString() + " ";
        private void addMsg(string str, string ChangefileName)
        {
            int isfile = ChangefileName.LastIndexOf('.');
            if (isfile > 0)
                ChangefileName = ChangefileName.Substring(isfile);
            //listBox记录超过200则清空,以防卡死
            if (listBox1.Items.Count >= 200)
                listBox1.Items.Clear();
            if (fileName == "")
                fileName = System.DateTime.Now.ToString("yyyyMMddHHmmss") + ".txt";
            else
            {
                string tmp = fileName.Substring(0, 8);
                if (!tmp.Contains(System.DateTime.Today.ToString("yyyyMMdd")))
                    fileName = System.DateTime.Now.ToString("yyyyMMddHHmmss") + ".txt";
            }

            System.IO.File.AppendAllText(@"./log/" + fileName, str + System.Environment.NewLine);
            listBox1.Items.Add(str);
            listBox1.SelectedIndex = listBox1.Items.Count - 1;
        }
      
        #endregion    

        

        private void listBox1_SelectedIndexChanged(object sender, EventArgs e)
        {

        }

        private void Form1_Load_1(object sender, EventArgs e)
        {
            if (!System.IO.Directory.Exists(@"./log"))
                System.IO.Directory.CreateDirectory(@"./log");
        }

        private void button1_Click(object sender, EventArgs e)
        {
            try
            {
                
                NotifyFilters nt = NotifyFilters.LastWrite;
                fileSystemWatcher1.Path =@"c:\shuchu";
                fileSystemWatcher1.NotifyFilter = nt;

                fileSystemWatcher1.EnableRaisingEvents = true;
                button1.Enabled = false;
                button2.Enabled = true;
                listBox1.Items.Clear();
                listBox1.Items.Add("开始监控...");
                listBox1.Items.Add("所有监控信息将写入log目录中。");

            }
            catch (System.Exception e1)
            {
                addMsg(e1.Message, "sdfsfsdfsdfds.sdfsdfsdfsdfsdfsdfsdfd");
            }
        }
        public string m=@"c:\shuchu\file_second.txt";        
        public string n=@"c:\shuchu\2.txt";
        public string L = @"c:\shuchu\file_second0.txt";
        private void button2_Click(object sender, EventArgs e)
        {
            button1.Enabled = true;
            button2.Enabled = false;
        }

        private void fileSystemWatcher1_Changed(object sender, FileSystemEventArgs e)
        {
           string v = e.FullPath;
            j++;           
            int i = comboBox1.SelectedIndex;
            switch (v)
            {
                case @"c:\shuchu\file_second.txt":
                    comboBox1.Text = "172.23.209.2:3924";
                    i = comboBox1.SelectedIndex;
                    break;
                case @"c:\shuchu\4-1.txt":
                    comboBox1.Text = "172.19.229.6:4001";
                    i = comboBox1.SelectedIndex;
                    break;
            }
            //if (comboBox1.Text != "172.19.229.1:4002")
            //{
             // comboBox1.Text = "172.19.229.1:4002";
              //  i = comboBox1.SelectedIndex;//通过选中选项来改变索引值,进而建立起服务器与客户端的通道)
          // }   
            
                //addMsg(str1 + e.FullPath + " TYPE:" + e.ChangeType, e.Name);
                if (j == 2)
                {
                    addMsg(str1 + e.FullPath + " TYPE:" + e.ChangeType, e.Name);
                StreamReader sr = new StreamReader(e.FullPath, Encoding.Default);
                String line = sr.ReadLine();
                while (line != null)
                {
                    richTextBox2.Text += line + "\n";
                    line = sr.ReadLine();
                }                
               sr.Close();
               for (int m = 0; m < friends.Count; m++)
                   senddata((MyFriend)friends[m], richTextBox2.Text.Trim());
               richTextBox2.Clear();
                j = 0;
                }
         }

        private void richTextBox2_TextChanged(object sender, EventArgs e)
        {

        }

        }
    }



  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值