Socket

int port = 6000;
            string host = "127.0.0.1";

            IPAddress ip = IPAddress.Parse(host);
            IPEndPoint ipe = new IPEndPoint(ip, port);   //终结点,服务器的地址和端口号

            Socket sSocket = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp);
            sSocket.Bind(ipe);
            sSocket.Listen(0);
            Console.WriteLine("监听已经打开,请等待");

            //receive message
            Socket serverSocket = sSocket.Accept();
            Console.WriteLine("连接已经建立");
            string recStr = "";
            byte[] recByte = new byte[4096];
            int bytes = serverSocket.Receive(recByte, recByte.Length, 0);
            recStr += Encoding.ASCII.GetString(recByte, 0, bytes);

            //send message
            Console.WriteLine("服务器端获得信息:{0}", recStr);
            string sendStr = "send to client :hello";
            byte[] sendByte = Encoding.ASCII.GetBytes(sendStr);
             
            //server服务器发送数据,以字节格式发送
            serverSocket.Send(sendByte, sendByte.Length, 0);
            serverSocket.Close();
            sSocket.Close();

客户端

 

int port = 6000;
            string host = "127.0.0.1";//服务器端ip地址

            IPAddress ip = IPAddress.Parse(host);
            IPEndPoint ipe = new IPEndPoint(ip, port);

            Socket clientSocket = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp);
            clientSocket.Connect(ipe);// 客户端连接服务器

            //send message
            string sendStr = "send to server : hello,ni hao";
            byte[] sendBytes = Encoding.ASCII.GetBytes(sendStr);
            clientSocket.Send(sendBytes); // 客户端发送数据// 字节格式 //Encoding.ASCII.GetByges(string str);

            //receive message
            string recStr = "";
            byte[] recBytes = new byte[4096];
            int bytes = clientSocket.Receive(recBytes, recBytes.Length, 0);
            recStr += Encoding.ASCII.GetString(recBytes, 0, bytes);
            Console.WriteLine(recStr);

            clientSocket.Close();

异步方法

using System;
using System.Collections;
using System.Collections.Generic;
using System.Linq;
using System.Net;
using System.Net.Sockets;
using System.Text;
using System.Threading.Tasks;

namespace AsyncClientSocket
{
    class Program
    {
        static void Main(string[] args)
        {

        }
        Socket clientSocket = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp);
        private byte[] MsgBuffer=new byte[2048];

        public void ConnectServer()
        {
            int port = 6000;
            string host = "127.0.0.1";

            IPAddress ip = IPAddress.Parse(host);
            IPEndPoint ipe = new IPEndPoint(ip, port);

            //clientSocket.Connect(ip, port);

        }

        public void Connect(IPAddress ip,int port)
        {
            this.clientSocket.BeginConnect(ip, port, new AsyncCallback(ConnectCallBack), this.clientSocket);
        }

        private void ConnectCallBack(IAsyncResult ar)
        {
            try
            {
                Socket handler = (Socket)ar.AsyncState;
                handler.EndAccept(ar);

            }
            catch(SocketException ex)
            {

            }
        }

        public void Send(string data)
        {
            Send(Encoding.UTF8.GetBytes(data));

        }

        private void Send(byte[] byteData)
        {
            try
            {
                int length = byteData.Length;
                byte[] head = BitConverter.GetBytes(length);
                byte[] data = new byte[head.Length + byteData.Length];
                Array.Copy(head, data, head.Length);
                Array.Copy(byteData, 0, data, head.Length, byteData.Length);
                this.clientSocket.BeginSend(data, 0, data.Length, 0, new AsyncCallback(SendCallback), this.clientSocket);



            }
            catch
            {

            }
        }

        private void SendCallback(IAsyncResult ar)
        {
            try
            {
                Socket handler = (Socket)ar.AsyncState;
                handler.EndSend(ar);
            }
            catch (SocketException ex)
            { }
        }

        public void ReceiveData()
        {
            clientSocket.BeginReceive(MsgBuffer, 0, MsgBuffer.Length, 0, new AsyncCallback(ReceiveCallback), null);
        }

        private void ReceiveCallback(IAsyncResult ar)
        {
            try
            {
                int REnd = clientSocket.EndReceive(ar);
                if (REnd > 0)
                {
                    byte[] data = new byte[REnd];
                    Array.Copy(MsgBuffer, 0, data, 0, REnd);

                    //在此次可以对data进行按需处理

                    clientSocket.BeginReceive(MsgBuffer, 0, MsgBuffer.Length, 0, new AsyncCallback(ReceiveCallback), null);
                }
                else
                {
                    dispose();
                }
            }
            catch (SocketException ex)
            { }
        }

        private void dispose()
        {
            try
            {
                this.clientSocket.Shutdown(SocketShutdown.Both);
                this.clientSocket.Close();
            }
            catch (Exception ex)
            { }
        }

        public Hashtable DataTable = new Hashtable();

        public void DataArrival(byte[] data,string ip)
        {
            try
            {
                 if(data.Length<12)// 按需判断
                {
                    lock (DataTable)
                    {
                        if (DataTable.Contains(ip))
                        {
                            DataTable[ip]=data;

                            return;
                        }
                    }
                }
                if (data[0] != 0x1F || data[1] != 0xF1)    //标志位(按需求编写)
                {
                    if (DataTable.Contains(ip))
                    {
                        if(DataTable!=null)
                        {
                            byte[] oldData = (byte[])DataTable[ip];  //取出粘包数据
                            if (oldData[0]!=0x1F)
                            {
                                return;
                            }
                            byte[] newData = new byte[data.Length + oldData.Length];
                            Array.Copy(oldData, 0, newData, 0, oldData.Length);
                            Array.Copy(data, 0, newData, oldData.Length, data.Length);

                            lock (DataTable)
                            {
                                DataTable[ip] = null;
                            }

                            DataArrival(newData, ip);
                            return;
                        }
                    }
                    return;
                }

                int revDataLength = data[2];//         打算发送的数据长度
                int revCount = data.Length;
                if(revCount>revDataLength)     //如果接收的数据长度大于发送的数据长度,说明存在多帧数据,继续处理
                {
                    byte[] otherData = new byte[revCount - revDataLength];
                    data.CopyTo(otherData, revCount - 1);

                }
            }
            catch (Exception)
            {

                throw;
            }
        }
    }
}

 

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

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值