C# socket 发送与接收

本文介绍了一个使用C#实现的Socket通信工具类,包括客户端发送文件到指定IP及端口的功能,以及服务端接收文件的功能。该工具类利用了.NET Framework提供的Socket API,并通过配置文件读取目标IP和端口。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

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

namespace SZTJ.PublicControl.Util
{
 public class SocketHelper
{
   private string path = Environment.CurrentDirectory + @"\barcode\barcode.xml";//要发送的文件

    private static string BarCodePrinterIP = ConfigurationManager.AppSettings["BarCodePrinterIP"];//自动贴码机ip地址
    private static int BarCodePrinterPort =Convert.ToInt32(ConfigurationManager.AppSettings["BarCodePrinterPort"]);//自动贴码机端口号

    private Socket s;

    public void listen()
    {
        string ip = BarCodePrinterIP;//远程IP
        IPAddress[] ih = Dns.GetHostAddresses(ip);       //获得IP列表
        IPAddress newip = ih[0];      //获取IP地址            
        int port =  BarCodePrinterPort;              //定义端口
        IPEndPoint Conncet = new IPEndPoint(newip, port);     //构造结点
        s = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp);                   //初始化socket 

        try
        {
            s.Connect(Conncet);      //连接远程服务器
            if (s.Connected)         //如果连接成功 s.Connected 则为true 否则为 false
            {
                //Console.WriteLine("连接成功");
                Thread t = new Thread(new ThreadStart(set)); //创建进程
                t.Start();                             //开始进程
                //Console.WriteLine("发送完毕");
            }
        }
        catch (NullReferenceException e)
        {
            //Console.WriteLine("{0}", e);
            ExceptionLogFunction.WriteLog(e);
        }
    }

    private void set()                       //创建set函数
    {
        //Console.WriteLine("开始发送数据");

        FileStream file = File.Open(path, FileMode.Open, FileAccess.Read);   //创建文件流
        byte[] b = new byte[1000000];//创建文件缓冲区,这里可以认为文件的最大值 
        int start = 0;
        int end = (int)file.Length; //获取文件长度文件传送如果有需要超过int的范围估计就要改写FileStream类了

        try
        {
            while (end != 0)
            {
                int count = file.Read(b, start, end);      //把数据写进流
                start += count;
                end -= count;
            }
            while (start != 0)
            {
                int n = s.Send(b, end, start, SocketFlags.None);  //用Socket的Send方法发送流
                end += n;
                start -= n;
            }

            file.Close();     //关闭文件流
            s.Close();        //关闭Socket
        }
        catch (NullReferenceException e)
        {
            //Console.WriteLine("{0}", e);
            ExceptionLogFunction.WriteLog(e);
        }
    }

    public void get()
    {
        string path = "d:\\socketRec.xml";  //接收的文件
        FileStream file = new FileStream(path, FileMode.OpenOrCreate, FileAccess.Write); //写入文件流
        TcpListener listen = new TcpListener(BarCodePrinterPort);  //监听端口
        Socket s1 = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp);  //定义Socket并初始化
        try
        {
            listen.Start();//开始监听
            s1 = listen.AcceptSocket();            //获取Socket连接
            byte[] data = new byte[10000000];      //定义缓冲区
            int longer = data.Length;
            int start = 0;
            int mid = 0;
            if (s1.Connected)             //确定连接
            {
                //Console.WriteLine("连接成功");
                int count = s1.Receive(data, start, longer, SocketFlags.None);  //把接收到的byte存入缓冲区
                int size = count;
                mid += count;
                longer -= mid;
                while (count != 0)
                {
                    count = s1.Receive(data, mid, longer, SocketFlags.None);
                    mid += count;
                    longer -= mid;
                }
                file.Write(data, 0, size); //写入文件
                s1.Close();
                file.Close();
            }
        }
        catch (NullReferenceException e)
        {
            //Console.WriteLine("{0}", e);
            ExceptionLogFunction.WriteLog(e);
        }
    }
}
}
复制代码
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值