TCP/IP 通信

//————————Clinet.cs————————————

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.Sockets;
using System.Threading;

namespace TcpClinet
{
    public partial class Clinet : Form
    {
        public Clinet()
        {
            InitializeComponent();
        }

        //サーバーのホスト名とポート番号
        string host = "localhost";
        int port = 8001;

        private void SendButton_Click(object sender, EventArgs e)
        {
            Thread th = new Thread(SendData);
            th.Start();
        }

        private void SendData()
        {
            try
            {
                //文字コードを指定する
                System.Text.Encoding enc = System.Text.Encoding.UTF8;

                //TcpClientを作成し、サーバーと接続する
                TcpClient tcp = new TcpClient(host, port);
                Console.WriteLine("サーバーと接続しました。");

                //NetworkStreamを取得する
                System.Net.Sockets.NetworkStream ns = tcp.GetStream();

                //サーバーにデータを送信する
                //送信するデータを入力
                //string sendMsg = Console.ReadLine();
                string sendMsg = this.textBox1.Text;
                //何も入力されなかった時は切断する
                if (sendMsg == "")
                {
                    tcp.Close();
                    return;
                }
                //文字列をByte型配列に変換
                byte[] sendBytes = enc.GetBytes(sendMsg);
                //データを送信する
                ns.Write(sendBytes, 0, sendBytes.Length);
                Console.WriteLine(sendMsg);

                //サーバーから送られたデータを受信する
                System.IO.MemoryStream ms = new System.IO.MemoryStream();
                byte[] resBytes = new byte[1024];
                int resSize;
                do
                {
                    //データの一部を受信する
                    resSize = ns.Read(resBytes, 0, resBytes.Length);
                    //Readが0を返した時はサーバーが切断したと判断
                    if (resSize == 0)
                    {
                        Console.WriteLine("サーバーが切断しました。");
                        Console.ReadLine();
                        return;
                    }
                    //受信したデータを蓄積する
                    ms.Write(resBytes, 0, resSize);
                } while (ns.DataAvailable);
                //受信したデータを文字列に変換
                string resMsg = enc.GetString(ms.ToArray());

                ms.Close();
                Console.WriteLine(resMsg);

                var sp = resMsg.Split(',');
              this.Invoke(
               (MethodInvoker)delegate()
               {
                   this.textBox3.Text = sp[0];
                   this.textBox2.Text = sp[1];
               });

                //閉じる
                ns.Close();
                tcp.Close();
                Console.WriteLine("切断しました。");

                Console.ReadLine();
            }
            catch (Exception ex)
            {
                MessageBox.Show("送信失敗しました。");
            }
        }
    }
}

 

//——————————Server.cs————————————————

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.Sockets;
using System.Net;
using System.Threading;


namespace TcpStudy
{
    public partial class Server : Form
    {

        private const string ANumbers = "0123456789";
        private const int BitCount = 4;

        public Server()
        {
            InitializeComponent();
        }

        TcpClient tcp;
       TcpListener listener;
       NetworkStream ns;
        Thread th;
        System.Timers.Timer timer = new System.Timers.Timer();

        void StartButton_Click(object sender, EventArgs e)
        {
            this.StartButton.Enabled = false;
             //th = new Thread(GetDate);
            // th.IsBackground =true;
            //th.Start();
            this.timer.Interval = 20;
            timer.Enabled = true;


            //ローカルIPアドレスでListenを開始する
            string host = "localhost";
            int port = 8001;
            IPAddress ipAdd = Dns.GetHostEntry(host).AddressList[0];
            listener = new System.Net.Sockets.TcpListener(ipAdd, port);
            listener.Start();
            Console.WriteLine("Port{0}のListenを開始しました。", port);
            timer.Elapsed += new System.Timers.ElapsedEventHandler(Timer_Elapsed);
            //dataTh = new Thread(Results);
            //dataTh.Start();
        }

        private void GetDate()
        {
            try
            {
                //文字コードを指定する
                System.Text.Encoding enc = System.Text.Encoding.UTF8;

                //接続要求があったら受け入れる
                tcp = listener.AcceptTcpClient();
                Console.WriteLine("クライアントが接続しました。");
                //NetworkStreamを取得
                ns = tcp.GetStream();

                //クライアントから送られたデータを受信する
                System.IO.MemoryStream ms = new System.IO.MemoryStream();
                byte[] resBytes = new byte[1024];
                int resSize;
                do
                {
                    //データの一部を受信する
                    resSize = ns.Read(resBytes, 0, resBytes.Length);
                    //Readが0を返した時はクライアントが切断したと判断
                    if (resSize == 0)
                    {
                        Console.WriteLine("クライアントが切断しました。");
                        Console.ReadLine();
                        return;
                    }
                    //受信したデータを蓄積する
                    ms.Write(resBytes, 0, resSize);
                }
                while (ns.DataAvailable);
                //受信したデータを文字列に変換
                string resMsg = enc.GetString(ms.ToArray());

                if (this.IsHandleCreated)
                {
                    this.Invoke(
                        (MethodInvoker)delegate()
                        {
                            this.textBox1.Text = resMsg;
                        });
                }

                string serverData = this.GetServerData();
                this.Invoke(
                    (MethodInvoker)delegate()
                {
                    this.textBox2.Text = serverData;
                });
                Result result = this.ResultCheck(resMsg, serverData);
                string sendMsg = string.Format("{0}, Hit:{1} Blow:{2}",
                   serverData, result.HitCount, result.BlowCount);
                ms.Close();
                Console.WriteLine(resMsg);

                //クライアントにデータを送信する
                //string sendMsg = resMsg.Length.ToString() + "文字";
                //文字列をByte型配列に変換
                byte[] sendBytes = enc.GetBytes(sendMsg);
                //データを送信する
                ns.Write(sendBytes, 0, sendBytes.Length);
                Console.WriteLine(sendMsg);
                //閉じる
                ns.Close();
                tcp.Close();
            }
            catch
            {
               
            }

        }

        private void button1_Click(object sender, EventArgs e)
        {
            if (this.th != null)
            {
                this.th.Abort();

            }
            //リスナを閉じる
            listener.Stop();
            this.StartButton.Enabled = true;
            MessageBox.Show("サバ停止しました。");
        }

        void Timer_Elapsed(object sender, System.Timers.ElapsedEventArgs e)
        {
            this.GetDate();
        }

        /// <summary>
        /// データ取得
        /// </summary>
        private string GetServerData()
        {
                List<string> OutputList = new List<string>();
                //データ取得
                this.CombinationCollocate(OutputList, ANumbers, "", BitCount);

                // 取得リストをランダムする
                List<string> NewOutputList = new List<string>(OutputList);
                Random random = new Random();
                foreach (string item in OutputList)
                {
                    NewOutputList.Insert(random.Next(NewOutputList.Count), item);
                }
                Random rd = new Random();
                int k = rd.Next(OutputList.Count);
                return  OutputList[k];

 

        }

        /// <summary>
        /// 合わせ結果
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private Result ResultCheck(string clinetDate, string serverDate)
        {
            Result result = new Result();

            var charClient = clinetDate.ToCharArray();
            var charServer = serverDate.ToCharArray();

            int hitCount = 0;
            int blowCount = 0;
            for (int i = 0; i < 4; i++)
            {
                if (charClient[i] == charServer[i])
                {
                    result.HitCount++;
                    hitCount++;
                }
                else
                {
                    if (charServer.Contains(charClient[i]))
                    {
                        result.BlowCount++;
                        blowCount++;
                    }
                }
            }

            return result;

        }


        /// <summary>
        /// サーバデータ作成
        /// </summary>
        /// <param name="AStrings">保存リスト</param>
        /// <param name="ANumbers">数字範囲</param>
        /// <param name="APath">結果</param>
        /// <param name="ALen">桁数</param>
        public void CombinationCollocate(List<string> AStrings, string ANumbers, string APath, int ALen)
        {
            if (APath.Length >= ALen)
            {
                AStrings.Add(APath);
                return;
            }
            for (int i = 0; i < ANumbers.Length; i++)
            {
                string vNumbers = ANumbers.Remove(i, 1);
                CombinationCollocate(AStrings, vNumbers, APath + ANumbers.Substring(i, 1), ALen);
            }
        }

         class Result
        {
            public int HitCount
            {
                get;
                set;
            }
            public int BlowCount
            {
                get;
                set;
            }
        }

 

    }
}

 

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

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值