C# socket程序总结

来源:互联网 发布:克赛前来拜访 知乎 编辑:程序博客网 时间:2024/05/21 16:57




窗体1程序:

using System;using System.Collections.Generic;using System.ComponentModel;using System.Data;using System.Drawing;using System.Linq;using System.Net;using System.Net.Sockets;using System.Text;using System.Threading;using System.Threading.Tasks;using System.Windows.Forms;namespace frmsocket{    public partial class frmSetIP : Form    {        public Socket newclient;        public bool Connectedtest;        public delegate void MyInvoke(string str);        public frmSetIP()        {            InitializeComponent();        }        private void Form1_Load(object sender, EventArgs e)        {        }        public void Connect()        {            serverIP.Text = "192.168.1.200";            serverPort.Text = "4196";            byte[] data = new byte[1024];            newclient = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp);    //构造socket对象            string ipadd = serverIP.Text.Trim();        //输入IP地址            int port = Convert.ToInt32(serverPort.Text.Trim());     //输入端口号            IPEndPoint ie = new IPEndPoint(IPAddress.Parse(ipadd), port);       //表示网络端点                   try            {                newclient.Connect(ie);   //与服务器连接                 Connectedtest = true;            }            catch (SocketException e)            {                MessageBox.Show("连接服务器失败  " + e.Message);                return;            }        }        public void DisConnect()        //断开连接        {            newclient.Shutdown(SocketShutdown.Both);            newclient.Close();        }        private void ConnectButton_Click(object sender, EventArgs e)        {            Connect();            ConnectButton.Enabled = false;            DisableConnectButton.Enabled = true;            frmSeRe SeRe = new frmSeRe(this);                   SeRe.Show();            this.Hide();        }        private void DisableConnectButton_Click(object sender, EventArgs e)        {            DisConnect();            ConnectButton.Enabled = true;        }    }}

窗体2程序:

using System;using System.Collections.Generic;using System.ComponentModel;using System.Data;using System.Drawing;using System.Linq;using System.Net.Sockets;using System.Text;using System.Threading.Tasks;using System.Windows.Forms;namespace frmsocket{    public partial class frmSeRe : Form    {        frmSetIP SetIP;        public frmSeRe(frmSetIP SetIP)        {            InitializeComponent();            this.SetIP = SetIP;        }        private void SendButton_Click(object sender, EventArgs e)           //确认发送数据        {            int m_length = SendBox.Text.Length;            byte[] data = new byte[m_length];            data = Encoding.UTF8.GetBytes(SendBox.Text);            string data1 = SendBox.Text;            if (SetIP.newclient != null)            {                //int i = SetIP.newclient.Send(data);                this.SendData(data1);            }            ReceiveBox.Text = ReceiveMsg();        }        public bool SendData(string strData)                //发送数据        {            byte[] bytes = strToToHexByte(strData);            try            {                SetIP.newclient.Send(bytes);                return true;            }            catch            {                if (SetIP.newclient != null)                {                    SetIP.newclient.Shutdown(SocketShutdown.Both);                    SetIP.newclient.Close();                    if (SetIP.Connectedtest)                    {                        return SendData(strData);                    }                }            }            return false;        }        private byte[] strToToHexByte(string hexString)                 //字符串转数组        {            hexString = hexString.Replace(" ", "");            if ((hexString.Length % 2) != 0)                hexString += " ";            byte[] returnBytes = new byte[hexString.Length / 2];            for (int i = 0; i < returnBytes.Length; i++)                returnBytes[i] = Convert.ToByte(hexString.Substring(i * 2, 2).Trim(), 16);            return returnBytes;        }        public string ReceiveMsg()                             //接收数据        {            string strData = string.Empty;            int nLength = 0;            byte[] bytes = new byte[1024];            SetIP.newclient.ReceiveTimeout = 100;             //设置超时100            if (null != SetIP.newclient && SetIP.newclient.Connected)            {                try                {                    nLength = SetIP.newclient.Receive(bytes);                }                catch (SocketException)                {                }                for (int i = 0; i < nLength; i++)                {                    strData += bytes[i].ToString("X2");     //十六进制                }            }            return strData;        }    }}


0 0