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);
}
}
}
}
复制代码
C# socket 发送与接收
最新推荐文章于 2024-05-07 21:36:19 发布