码迷,mamicode.com
首页 > Windows程序 > 详细

c# tcplistener 与 client通信 服务端 今天写一下

时间:2015-06-15 18:08:10      阅读:165      评论:0      收藏:0      [点我收藏+]

标签:

using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Net;
using System.Net.Sockets;
using System.Runtime.CompilerServices;
using System.Text;
using System.Threading;



namespace GameServer {

    public class EngineUser {
        public string userName;
        public TcpClient Client;
        public StreamWriter Sw;
        public StreamReader Sr;

        public EngineUser(TcpClient client) {
            this.Client = client;
            NetworkStream netStream = client.GetStream();
            Sw = new StreamWriter(netStream, Encoding.UTF8);
            Sr = new StreamReader(netStream, Encoding.UTF8);
            this.userName = "";
        }
    }

    public class AnalysizeEngine : IDisposable {
        #region 多线程 singleton

        private static AnalysizeEngine _instance;
        private static readonly object LockObject = new object();

        public static AnalysizeEngine GetInstance() {
            if (_instance == null) {
                lock (LockObject) {
                    if (_instance == null) _instance = new AnalysizeEngine();
                }
            }
            return _instance;
        }
        #endregion

        #region  私有变量 将engine中的线程全部用变量声明,保存在这里,退出的时候,要全部结束!
        private TcpListener _listener;
        //todo:up not implemented
        #endregion

        #region 构造函数
        public AnalysizeEngine()
            : this("tcp engine") {
        }
        public AnalysizeEngine(String name) { }
        #endregion

        #region 属性事件
        public event HandleOverActionHandler Handle;
        public delegate void HandleOverActionHandler(String message);
        #endregion

        #region 成员方法

        #endregion

        #region 操作方法

        public AnalysizeEngine Start() {
            try {
                if (_listener == null)
                    _listener = new TcpListener(IPAddress.Parse(ConfigHelper.Get("localIp")),
                        Int32.Parse(ConfigHelper.Get("localPort")));
                _listener.Start();
            } catch (Exception ex) {
                LogHelper.Error(ex);
            }
            Thread m = new Thread(() => {
                GetInstance().Process();
            });
            m.Start();
            return this;
        }
        public void Process() {
            while (true) {
                TcpClient guest = _listener.AcceptTcpClient();
                EngineUser u= new EngineUser(guest);

                var thread = new Thread(f => {
                    EngineUser client = f as EngineUser;
                    if (client == null) return;
                    //read line 需要用while true循环!
                    while (true) {
                        string receiveString = client.Sr.ReadLine();
                        if(receiveString==null)return;

                        LogHelper.Info("成功接收:" + receiveString);
                        if (this.Handle != null) Handle(receiveString);
                        try {
                            #region 解析本次定位相关

                            string[] splitString = receiveString.Split(,);
                            if (!splitString[0].StartsWith("SLC"))
                                throw new ArgumentException("指令没有以SLC开头");
                            String[] parts = receiveString.Split(|);
                            if (parts.Length < 3) throw new ArgumentException("指令没有以|分隔3部分");
                            var total = parts[0].Length > 2 ? parts[0].Substring(2, parts[0].Length - 2) : "";
                            var verson = parts[2].Split({)[0];
                            var data = parts[1];
                            var subDatas = new List<String>();
                            data.Trim(new char[] { {, } }).Split(>).ToList().ForEach(t => {
                                subDatas.Add(
                                    t.TrimStart(
                                        <));
                            });
                            u.Sw.WriteLine("过程已处理!");
                            u.Sw.Flush();
                        }


                            #endregion              }

 catch (Exception ex) {
                            LogHelper.Error(ex);
                        }
                    }


                });
                thread.Start(u);
            }
        }
        public AnalysizeEngine Stop() {

            _listener.Stop();
            return this;
        }
        #endregion

        #region IDisposable 成员

        public void Dispose() {
            _listener.Stop();
            _instance = null;
            _listener = null;
        }
        #endregion
    }
}

 

c# tcplistener 与 client通信 服务端 今天写一下

标签:

原文地址:http://www.cnblogs.com/hualiu0/p/4578800.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!