php中文网 | cnphp.com

 找回密码
 立即注册

QQ登录

只需一步,快速开始

搜索
查看: 455|回复: 0

clientSocket:实现client的socket通信

[复制链接]

2620

主题

2627

帖子

9308

积分

管理员

Rank: 9Rank: 9Rank: 9

UID
1
威望
0
积分
6566
贡献
0
注册时间
2021-4-14
最后登录
2024-4-25
在线时间
666 小时
QQ
发表于 2022-5-8 09:55:03 | 显示全部楼层 |阅读模式
[mw_shl_code=c,true]using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading;
using System.Net;
using System.Net.Sockets;
using System.IO;
/*时间:2014-7-12
* 功能:socket发送接收数据,作为服务端
* 问题:发送一次成功,断开连接
*/


namespace ClientSocket
{
    class SocketComm
    {
        NetworkStream stream = null;
        TcpClient tcpClient = null;
        private string ClientIP = "";
        private int ClientPort;
        private Byte[] data = new Byte[4000];//读取的数据
        private Byte[] sData = new Byte[20 * 1024 * 1024];//发送的数据可以发送1024个字节=1Kb,共30Kb
        private Byte[] recBytes = new Byte[4000];//定义缓存区
        private Byte[] recBytes1 = new Byte[1024];//定义缓存区
        private Byte[] stringBytes = new Byte[5];//定义缓存区
        private Byte[] stopBytes = new Byte[1024];//定义缓存区
        private Byte[] numBytes = new Byte[1];//定义缓存区
        private int sDataLen = 0;
        private bool sendFile = false;

        public void Start(string ip, int port)
        {
            ClientIP = ip;
            ClientPort = port;
            Thread clientThread = new Thread(Receive);
            clientThread.Start();
            
        }
        public void SendData(byte[] data, int length)
        {
            sData = data;
            sDataLen = length;
        }
        public Byte[] TransferData
        {
            get { return data; }
        }
        public bool SendFile
        {
            get { return sendFile; }
            set
            {
                sendFile = value;
            }
        }
        private void Receive()
        {
            /************************IP地址***********************/
            IPAddress localAddr = IPAddress.Parse(ClientIP);//将IP地址字符串转换为IPAddress实例
            IPEndPoint ipe = new IPEndPoint(localAddr, ClientPort);//服务器主机的IP和Port,创建远程终结点
            /***********************************************/
            Byte[] sendBytes = Encoding.ASCII.GetBytes("Data");
            while (true)
            {
                try
                {
                    /********************发送请求***************************/
                    tcpClient = new TcpClient(ClientIP, ClientPort);
                    stream = tcpClient.GetStream();//创建新实例
                    numBytes[0] = 1;
                    /***********************************************/
                    if (tcpClient.Connected)//连接上
                    {
                        /************************发送接收数据***********************/
                        if(stream.CanWrite)
                        stream.Write(numBytes,0,1);
                        //if (stream.DataAvailable)
                        stream.Read(recBytes, 0, recBytes.Length);
                        Thread.Sleep(100);
                        data = recBytes;
                        if (sendFile)
                        {
                            sendFile = false;
                            stream.Write(sData, 0, sData.Length);
                            Thread.Sleep(100);
                        }
                        char[] charbytes = new char[5];
                        string fileNameStr = "";
                        //Console.WriteLine("\n接收到数据的前4位:");
                        for (int k = 0; k < 5; k++)//读取文件流中前4位并转成字符串
                        {
                            charbytes[k] = (char)recBytes[k];
                            fileNameStr += charbytes[k].ToString();
                            //Console.Write("{0}", (char)charbytes[k]);
                        }
                        if (fileNameStr == "Write")
                        {
                            WriteToFile();
                            for (int i = 0; i < 276; i++)
                                Console.Write("{0}", (char)recBytes[i + 5]);
                            Console.WriteLine("写Config.ini文件数据完毕");
                        }
                    }
                    tcpClient.Close();
                    stream.Close();

                }
                catch (Exception e)
                {
                    Console.WriteLine("SocketException---------------:{0}", e);
                    //client.Close();
                }
            }
        }
        private void delay(int x)
        {
            for (int i = 0; i < x; i++)
            {
                for (int j = 0; j < 100; j++)
                    i++;
            }
        }
        private void WriteToFile()
        {
            FileStream fs = null;
            string currentPath = System.Environment.CurrentDirectory;
            try
            {
                fs = new FileStream(currentPath + @"\\Config.ini", FileMode.Create, FileAccess.Write);//文件流实例化
                BinaryWriter bw = new BinaryWriter(fs);
                byte[] bbytes = new byte[276];//第5位表示传输文件的长度
                for (int i = 0; i < bbytes.Length; i++)//将bytes[]中的字符强制转成字符串,并且是动态长度
                {
                    bbytes = recBytes[i + 6];//byte类型转成char类型
                }
                bw.Write(bbytes);//传输的是字节数组型
                bw.Close();
                fs.Close();
            }
            catch (Exception e)
            {
                Console.WriteLine("--------------" + e.Message);
            }
        }
    }
}
[/mw_shl_code]





上一篇:php中 getDoctype方法代碼示例
下一篇:crc16代码实现
回复

使用道具 举报

您需要登录后才可以回帖 登录 | 立即注册

本版积分规则

QQ|php中文网 | cnphp.com ( 赣ICP备2021002321号-2 )51LA统计

GMT+8, 2024-4-25 15:14 , Processed in 0.177193 second(s), 36 queries , Gzip On.

Powered by Discuz! X3.4 Licensed

Copyright © 2001-2020, Tencent Cloud.

申明:本站所有资源皆搜集自网络,相关版权归版权持有人所有,如有侵权,请电邮(fiorkn@foxmail.com)告之,本站会尽快删除。

快速回复 返回顶部 返回列表