基于C#的socket编程的TCP同步实现

来源:互联网 发布:linux怎么查看log文件 编辑:程序博客网 时间:2024/06/05 19:15

如何搭建自己的异步TCP winform:


*********************************************************** 共同过程*************************************************************

1. 构造socket对象

<span style="font-size:18px;">Socket socket = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp);</span>

                     AddressFamily:(枚举类型)指定 System.Net.Sockets.Socket 类的实例可以使用的寻址方案。成员InterNetwork表示IPv4地址。

SocketType:(枚举类型)指定 System.Net.Sockets.Socket 类的实例表示的套接字类型。成员Stream表示支持可靠、双向、基于连接的字节流,而不重复数据,也不保留边界。 此类型的 Socket 与单个对方主机通信,并且在通信开始之前需要建立远程主机连接。

                  ProtocolType:(枚举类型)指定System.Net.Sockets.Socket类支持的协议。常用的有TCP,UDP

2.构造IPEndPoint对象

<span style="font-size:12px;"><span style="font-size:14px;"> IPEndPoint ipEndPoint=new IPEndPoint(IPAddress address, int port</span>);</span>

                     address: 一个 System.Net.IPAddress。

                port: 与 address 关联的端口号,或为 0 以指定任何可用端口。 port 以主机顺序排列。

                     补充:

                     IPAddress.Parse()方法可以将IP地址字符串转化为IPAddress实例。

                     //如何获取本机IP address

<strong>          </strong>string hostName = Dns.GetHostName();  //get the hostname          IPHostEntry ipEntry = Dns.GetHostByName(hostName);//get the IP arry by the hostName          string localHostIP = ipEntry.AddressList[0].ToString();//get the ip <strong></strong>

*****************************************************区别*************************************************************************

对于Server端:

1.Socket对象和IPEndPoint对象通过Bind()方法绑定。                

<span style="font-size:14px;"><strong> socket.Bind(endPoint);</strong></span>

2.socket.Listen()方法将服务器端置于侦听状态。

<span style="font-size:14px;"><strong> socket.Listen(1);//参数</strong></span><span style="font-family:Courier New;font-size:14px;background-color: rgb(240, 240, 240);"><strong>backlog: 挂起连接队列的最大长度。</strong></span>

注:此时服务器端会处于阻塞状态。(在调用返回结果前,当前线程挂起,cpu不给线程分配时间片,线程停止)


对于Client端:

1.Socket对象通过.connect()方法连接server端的IPEndPoint对象。

注:连接成功server端停止阻塞。

*************************************************消息发送与接收***************************************************************

Socket.Receive(receiveByte,receiveByte.Length, 0);//接受指定字节的数据,并存入指定的字节数组。

Socket.Send(sendByte,sendByte.Length, 0);//从指定的字节数组发送指定字节的数据。

注:如何实现字符串到字节数组的转换:

    string strInfo = Encoding.BigEndianUnicode.GetString(receiveByte);

    字节数组到字符串的转换:

    sendByte = Encoding.BigEndianUnicode.GetBytes(sendStr.ToCharArray());

******************************************代码***************************************************

-------- code of server---------

using System;using System.Text;using System.Windows.Forms;using System.Net;using System.Net.Sockets;using System.Threading;namespace socket_Server{    public partial class Form1 : Form    {        //public Socket socket;        public Socket socket;        bool flag = true;        public Form1()        {            CheckForIllegalCrossThreadCalls = false;            InitializeComponent();         }        private void button1_Click(object sender, EventArgs e)        {            IPEndPoint endPoint = new IPEndPoint(IPAddress.Parse(textBox2.Text), Convert.ToInt32((textBox3.Text).Trim()));//192.168.253.1//192.168.173.1            socket = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp);            socket.Bind(endPoint);            socket.Listen(1);            socket = socket.Accept();            Thread startServer = new Thread(Process);            startServer.Start();        }        private void Process()        {            if (socket.Connected)            {                while (flag)                {                    byte[] receiveByte = new byte[64];                    try                     { socket.Receive(receiveByte, receiveByte.Length, 0);                    string strInfo = Encoding.BigEndianUnicode.GetString(receiveByte);                    textBox1.AppendText(strInfo + "\r\n");                    }                    catch { }                       }            }            else { MessageBox.Show("3"); }        }        private void button2_Click(object sender, EventArgs e)        {            try            {                Byte[] sendByte = new Byte[64];                string sendStr = textBox4.Text;                sendByte = Encoding.BigEndianUnicode.GetBytes(sendStr.ToCharArray());                socket.Send(sendByte, sendByte.Length, 0);            }            catch { }        }        private void button3_Click(object sender, EventArgs e)        {            socket.Close();            //socket.Close();        }    }}

-----code of Client--------

<span style="font-size:12px;">using System;using System.Net;using System.Net.Sockets;using System.Text;using System.Threading;using System.Windows.Forms;namespace socketClient{    public partial class Form1 : Form    {        public Socket socket;        //public Socket socket;        bool flag = true;        public Form1()        {            CheckForIllegalCrossThreadCalls = false;            InitializeComponent();        }        private void button1_Click(object sender, EventArgs e)        {            try            {                IPEndPoint endPoint = new IPEndPoint(IPAddress.Parse(textBox2.Text), Convert.ToInt32(textBox3.Text.Trim()));                socket = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp);                socket.Connect(endPoint);                Thread connectServer = new Thread(Process);                connectServer.Start();            }            catch { }        }        public void Process()        {            if (socket.Connected)            {                while (flag)                {                    byte[] receiveByte = new byte[64];                    try                     {                        socket.Receive(receiveByte, receiveByte.Length, 0);                        string strInfo = Encoding.BigEndianUnicode.GetString(receiveByte);                        textBox1.AppendText(strInfo + "\r\n");                    }                    catch { }                                   }            }            else { }        }        private void button3_Click(object sender, EventArgs e)        {            try            {                Byte[] sendByte = new Byte[64];                string sendStr = textBox4.Text;                sendByte = Encoding.BigEndianUnicode.GetBytes(sendStr.ToCharArray());                socket.Send(sendByte, sendByte.Length, 0);            }            catch { }        }        private void button2_Click(object sender, EventArgs e)        {            try            {                socket.Close();                //socket.Close();            }            catch { }            //finally { this.Close(); }        }    }}</span>
















     


0 0
原创粉丝点击