SOCKET与tpc/ip 通讯的实列

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;
using System.Runtime.InteropServices;
using System.Text.RegularExpressions;

namespace SocketClient
{
    public partial class frmSocketClient : Form
    {
        public frmSocketClient()
        {
            InitializeComponent();
        }
        Socket socketSend;
        private void btnClick_Click(object sender, EventArgs e)
        {



            try
            {
                //创建客户端Socket,获得远程ip和端口号
                socketSend = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp);
                IPAddress ip = IPAddress.Parse(txtIP.Text);
                IPEndPoint point = new IPEndPoint(ip, Convert.ToInt32(txtport.Text));

                socketSend.Connect(point);
                ShowMsg("连接成功!");
                //开启新的线程,不停的接收服务器发来的消息
                Thread c_thread = new Thread(Received);
                c_thread.IsBackground = true;
                c_thread.Start();
            }
            catch (Exception)
            {
                ShowMsg("IP或者端口号错误...");
            }
 
         }
        void ShowMsg(string str)
         {
             textConnect.AppendText(str + "\r\n");
        }
        /// <summary>
        /// 接收服务端返回的消息
        /// </summary>
       void Received()
         {
            while (true)
             {
                try
               {

                     byte[] buffer = new byte[1024 * 1024 * 3];
                     //实际接收到的有效字节数
                    int len = socketSend.Receive(buffer);
                    if (len == 0)
                     {
                         break;
                     }
                    string str =Encoding.UTF8.GetString(buffer, 0, len);
                     ShowMsg(socketSend.RemoteEndPoint + ":" + str);
                }
                catch { }
            }
        }
       

        /// <summary>
         /// 向服务器发送消息
         /// </summary>
         /// <param name="sender"></param>
         /// <param name="e"></param>
       private void btnSend_Click(object sender, EventArgs e)
       {
           try
           {

               try
               {
                   string msg = textBox2.Text;
                   //string data = ChangeLan(msg);//把输入的字符串转换成二进制
                   //string len = ((msg.Length) * 2).ToString();//长度
                   //StringBuilder sb = new StringBuilder();
                   //sb.Append("FF FF FF FF FF FF 00 00 00 00 ");
                   //sb.Append(" 78 34 01 00 ");
                   //sb.Append(" 29");
                   //sb.Append(" 12 F2 00 00 00 00 00 00  ");
                   //sb.Append(len+" 00");//len
                   //sb.Append(" 01 02 00 03 10 00  "+data);//data
                   //sb.Append(" 1E D7");//check
                   //sb.Append(" A5");
                   byte[] buffer = HexStringToByteArray(msg.ToString());//把二进制转换成16进制进行发送
                   socketSend.Send(buffer);
               }
               catch { }
             
           }
           catch { }
       }

        //把二进制转换成16进制发送通讯
       public static byte[] HexStringToByteArray(string s)
       {
           s = s.Replace(" ", "");
           byte[] buffer = new byte[s.Length / 2];
           for (int i = 0; i < s.Length; i += 2)
               buffer[i / 2] = (byte)Convert.ToByte(s.Substring(i, 2), 16);
           return buffer;
       }
       //UTF-8转化为GB2312
        public  static string ChangeLan(string text){
             byte[] bytes = System.Text.Encoding.GetEncoding("gb2312").GetBytes(text);
              string s = "";
              for (int i = 0; i < bytes.Length - 1; i++)
              {
                  string s1 = string.Format("{0:x2}", bytes[i].ToString("X2").PadLeft(4, '0'));
                  s = s + s1 ;
              }
             //字符串切割,每俩个数字中间加个空格
            string result = Regex.Replace(s, @".{2}", "$0 ");
            return result;
        }

       private void frmSocketClient_Load(object sender, EventArgs e)
       {
             Control.CheckForIllegalCrossThreadCalls = false;
       }
 

    }
}

 

 

2
界面

 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值