#region Socket客户端与MES通讯
public Socket socketclient; //客户端
public bool client = false;
public string tiaoma;//条码
public string bianhao;//设备编号
public string jieguo;//结果
public string tupianname;//图片文件名
public string cameraInfo;
public string mesbarcode;
bool rec1 = false;
void SocketConnect()//通讯连接
{
try
{
ReadMesIPCfg(out string _IP, out string _IPPoint);
socketclient = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp);
//IPAddress ip = IPAddress.Parse(TXTIP.Text.ToString());
IPAddress ip = IPAddress.Parse(_IP);//192.168.53.138
IPEndPoint point = new IPEndPoint(ip,Convert.ToInt32(_IPPoint));
//Console.WriteLine(_IP + Convert.ToInt32(_IPPoint));
socketclient.Connect(point);
client = true;
//MessageBox.Show("mes连接成功");
//ShowMessageToList("mes连接成功");
AppendTextToBox1("mes服务器连接成功", Color.Black);
}
catch
{
//ShowMessageToList("MES服务器连接失败!");
AppendTextToBox1("MES服务器连接失败!", Color.Red);
}
}
public void ReciveB1()//数据接收0
{
//while (true)
//{
try
{
byte[] buffer = new byte[1024];
int r = socketclient.Receive(buffer);
//实际接受有效字节数
if (r == 0)
return;
//接收的相机数据
// string strRev = Encoding.UTF8.GetString(buffer, 0, r);
//string strRev = Encoding.UTF32.GetString(buffer, 0, r);
string strRev = Encoding.ASCII.GetString(buffer, 0, r);
AppendTextToBox1($"MES回传信息:{strRev}", Color.Black);
if (strRev == "active")
ReciveB1();
else
{
if (strRev != null)
{
jieguo = strRev;
POSif = true;
if (strRev == "Y")
{
messtr = "K";
//ShowMessageToList($"条码合规:{strRev}");
//rec1 = true;
//MessageBox.Show($"条码合规:{strRev}");
AppendTextToBox1($"条码合规:{strRev}", Color.Black);
}
else
{
messtr = "G";
//ShowMessageToList("条码不合规!");
//MessageBox.Show($"条码不合规:{strRev}");
AppendTextToBox1($"条码不合规:{strRev}", Color.Red);
//DoCameraScanBar();
}
}
else
{
//ShowMessageToList("MES回复条码合规性有误!");
AppendTextToBox1("MES回复条码合规性有误!", Color.Red);
}
}
// if (textBox1.Text == "")
// MessageBox.Show("触发指令设置为空!");
// else
// {
//if (strRev == textBox1.Text)
//if (strRev == "Y")
//{
// job1run();
// //Control.CheckForIllegalCrossThreadCalls = false;
// //Thread thread1 = new Thread(new ThreadStart(job1run));
// //thread1.IsBackground = true;
// //thread1.Start();
//}
// }
}
catch
{
AppendTextToBox1("接收MES条码合规性数据异常!", Color.Red);
}
//}
}
public void ReciveB2()//数据接收0
{
//while (true)
//{
try
{
byte[] buffer = new byte[1024];
int r = socketclient.Receive(buffer);
//实际接受有效字节数
if (r == 0)
return;
//接收的相机数据
// string strRev = Encoding.UTF8.GetString(buffer, 0, r);
//string strRev = Encoding.UTF32.GetString(buffer, 0, r);
string strRev = Encoding.ASCII.GetString(buffer, 0, r);
if (strRev != null)
{
if (strRev == "Y")
{
//m_tcpServer.SendToClient("Y");
//MessageBox.Show($"Mes正确解析报文:{strRev}");
AppendTextToBox1($"Mes正确解析报文:{strRev}", Color.Black);
}
else
{
//m_tcpServer.SendToClient("N2");
// MessageBox.Show($"Mes解析报文失败,错误信息:{strRev}!");
AppendTextToBox1($"Mes解析报文失败,错误信息:{strRev}!", Color.Red);
//MessageBox.Show(strRev);
}
}
else
{
AppendTextToBox1("MES回复解析报文信息有误!", Color.Red);
}
// if (textBox1.Text == "")
// MessageBox.Show("触发指令设置为空!");
// else
// {
//if (strRev == textBox1.Text)
//if (strRev == "Y")
//{
// job1run();
// //Control.CheckForIllegalCrossThreadCalls = false;
// //Thread thread1 = new Thread(new ThreadStart(job1run));
// //thread1.IsBackground = true;
// //thread1.Start();
//}
// }
}
catch
{
AppendTextToBox1("接收MES解析报文信息数据异常!", Color.Red);
}
// }
}
public void SendB(string str)//Socket发送数据
{
byte[] buffer = System.Text.Encoding.ASCII.GetBytes(str);
if (client)
socketclient.Send(buffer);
}
public void M105send(string barcode)
{
tiaoma = barcode;
mesbarcode = "M105" + tiaoma;
SendB(mesbarcode);
ReciveB1();
}
public void M106send()
{
bianhao = "M80";
//d = ImageSaveHelper.ImageInfo;
//string v = d.Replace(@"\", "//");
tupianname = ImageSaveHelper.ImageInfo.Replace("//",@"\");
ftpauto(ImageSaveHelper.ImageInfo);
cameraInfo = "M106" + tiaoma + "," + bianhao + "," + jieguo + "," + tupianname;
SendB(cameraInfo);
ReciveB2();
}
public void M106sendtest()
{
bianhao = "M80";
//jieguo = "ok";
//d = ImageSaveHelper.ImageInfo;
//string v = d.Replace(@"\", "//");
tupianname = "imagename.jpg";//ImageSaveHelper.imagename;
ftpautotest();
cameraInfo = "M106" + tiaoma + "," + bianhao + "," + jieguo + "," + tupianname;
SendB(cameraInfo);
ReciveB2();
}
#endregion
#region
using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Net;
namespace Welding.UI
{
public class FTPHelper
{
/// <summary>
/// FTP的服务器地址,格式为ftp://192.168.1.234:8021/。
/// </summary>
private string FTPCONSTR { get; set; }
/// <summary>
/// //FTP服务器的用户名
/// </summary>
private string FTPUSERNAME { get; set; }
/// <summary>
/// //FTP服务器的密码
/// </summary>
private string FTPPASSWORD { get; set; }
public FTPHelper(string ip, string username, string password, string port )
{
FTPCONSTR = string.Format("{0}://{1}:{2}/", "ftp", ip, port);
FTPUSERNAME = username;
FTPPASSWORD = password;
}
#region 本地文件上传到FTP服务器
/// <summary>
/// 上传文件到远程ftp
/// </summary>
/// <param name="path">本地的文件目录</param>
/// <param name="name">文件名称</param>
/// <returns></returns>
public bool UploadFile(string path, string name)
{
FileInfo f = new FileInfo(path);
path = FTPCONSTR + name;//这个路径是我要传到ftp目录下的这个目录下
FtpDirectoryAndFile(path);
FtpWebRequest reqFtp = (FtpWebRequest)FtpWebRequest.Create(new Uri(path));
reqFtp.Method = WebRequestMethods.Ftp.UploadFile;
reqFtp.UsePassive = false;//只需要添加这一句话
reqFtp.UseBinary = true;
reqFtp.Credentials = new NetworkCredential(FTPUSERNAME, FTPPASSWORD);
reqFtp.KeepAlive = false;
reqFtp.Method = WebRequestMethods.Ftp.UploadFile;
reqFtp.ContentLength = f.Length;
int buffLength = 2048;
byte[] buff = new byte[buffLength];
int contentLen;
FileStream fs = f.OpenRead();
try
{
Stream strm = reqFtp.GetRequestStream();
contentLen = fs.Read(buff, 0, buffLength);
while (contentLen != 0)
{
strm.Write(buff, 0, contentLen);
contentLen = fs.Read(buff, 0, buffLength);
}
strm.Close();
fs.Close();
return true;
}
catch (Exception ex)
{
return false;
}
}
#endregion
#region ftp端目录不存在则自动创建文件夹
/// 判断ftp上是否有指定的文件目录,没有创建
/// 指定路径
public static void FtpDirectoryAndFile(string ftpPath)
{
int start = "ftp://192.168.58.253:21/".Length;
int end = ftpPath.LastIndexOf("/") - start;
string fullDir = ftpPath.Substring(start, end);
string[] dirs = fullDir.Split('/');
if (dirs != null && dirs.Length > 0)
{
string curDir = "ftp://192.168.58.253:21/";
for (int i = 0; i < dirs.Length; i++)
{
string dir = dirs[i];
if (dir != null && dir.Length > 0)
{
bool isContained = FtpDirIsExists(curDir, dir);
if (isContained)
{
curDir += dir + "/";
continue;
}
else
{
FtpMakeDir(curDir + dir);
curDir += dir + "/";
}
}
}
}
}
/// 判断ftp上的文件目录是否存在
/// 要判断的ftp上的文件目录路径
/// ftp上的文件目录路径中是否包含该文件夹名称
/// true 包含,false 不包含
public static bool FtpDirIsExists(string dirName, string folderName)
{
//string url = "ftp://" + FtpServerIP + "/" + dirName;
FtpWebRequest ftpWebRequest = (FtpWebRequest)WebRequest.Create(new Uri(dirName));
ftpWebRequest.UseBinary = true;
ftpWebRequest.Credentials = new NetworkCredential("ftpuser", "userftp");
ftpWebRequest.Method = WebRequestMethods.Ftp.ListDirectory;
System.IO.StreamReader streamReader = null;
System.IO.Stream responseStream = null;
bool isContained = false;
try
{
using (FtpWebResponse ftpWebResponse = (FtpWebResponse)ftpWebRequest.GetResponse())
{
responseStream = ftpWebResponse.GetResponseStream();
streamReader = new StreamReader(responseStream);
string nameList = streamReader.ReadToEnd();
streamReader.Close();
responseStream.Close();
string[] nameArr = nameList.Replace("\r\n", "#").Split(new string[] { "#" }, StringSplitOptions.RemoveEmptyEntries);
for (int i = 0; i < nameArr.Length; i++)
{
if (nameArr[i].Equals(folderName))
{
isContained = true;
break;
}
}
return isContained;
}
}
catch (Exception ex)
{
if (streamReader != null)
{
streamReader.Close();
}
if (responseStream != null)
{
responseStream.Close();
}
return false;
}
}
/// 在FTP上创建目录
/// 要创建的目录名
public static bool FtpMakeDir(string dirName)
{
FtpWebResponse response = null;
StreamReader reader = null;
try
{
//string uri = FtpServerIP + DateTime.Now.ToString("yyyyMMddHHmmss") + fileInfo.Name;
FtpWebRequest reqFTP = (FtpWebRequest)WebRequest.Create(new Uri(dirName));
reqFTP.Credentials = new NetworkCredential("ftpuser", "userftp");
//reqFTP.KeepAlive = false;
reqFTP.Method = WebRequestMethods.Ftp.MakeDirectory;
reqFTP.UseBinary = true;
response = (FtpWebResponse)reqFTP.GetResponse();
reader = new StreamReader(response.GetResponseStream());
string returnValue = reader.ReadToEnd();
response.Close();
reader.Close();
return true;
}
catch (Exception ex)
{
if (response != null)
{
response.Close();
}
if (reader != null)
{
reader.Close();
}
return false;
}
}
#endregion
}
}
FTP传输
public void ftpauto(string LocalPath)
{
ReadFTPCfg(out string IP, out string Port, out string UeseName, out string Password);
string ftpIP = IP;
string ftpPort = Port;
string ftpUserName = UeseName;
string ftpPassword = Password;
string localPath = LocalPath;//本地图片地址
string remotePath = ((localPath.Substring(3).Replace("\\", "/")).Replace("//", @"/")).Replace(@"\", @"/");//FTP端的存储地址
FTPHelper FTPHelper = new FTPHelper(ftpIP, ftpUserName, ftpPassword, ftpPort);
bool uploadresult = FTPHelper.UploadFile(localPath, remotePath);
Console.WriteLine(uploadresult);
}
public void ftpautotest()
{
ReadFTPCfgtest(out string IP, out string Port, out string UeseName, out string Password, out string LocalPath);
string ftpIP = IP;
string ftpPort = Port;
string ftpUserName = UeseName;
string ftpPassword = Password;
string localPath = LocalPath;//本地图片地址
string remotePath = ((localPath.Substring(3).Replace("\\", "/")).Replace("//", @"/")).Replace(@"\", @"/");//FTP端的存储地址
FTPHelper FTPHelper = new FTPHelper(ftpIP, ftpUserName, ftpPassword, ftpPort);
bool uploadresult = FTPHelper.UploadFile(localPath, remotePath);
Console.WriteLine(uploadresult);
}
#endregion