void Bind_Write_End(IAsyncResult ar) { Bind_SO stateObj = (Bind_SO)ar.AsyncState; try { stateObj.UpdateContext(); NStream.EndWrite(ar); //------------------------------------ // Read the response from proxy server. // NStream.BeginRead( _response, 0, 8, new AsyncCallback(Bind_Read_End), stateObj); } catch (Exception e) { stateObj.Exception = e; stateObj.SetCompleted(); } }
void Connect_Read_End(IAsyncResult ar) { Connect_SO stateObj = (Connect_SO)ar.AsyncState; try { stateObj.UpdateContext(); int num = NStream.EndRead(ar); stateObj.ReadBytes += num; if (stateObj.ReadBytes < 8) { //------------------------------------ // Read the response from proxy server. // NStream.BeginRead(_response, stateObj.ReadBytes, 8 - stateObj.ReadBytes, new AsyncCallback(Connect_Read_End), stateObj); } else { VerifyResponse(); stateObj.SetCompleted(); } } catch (Exception e) { stateObj.Exception = e; stateObj.SetCompleted(); } }
void Connect_Connect_End(IAsyncResult ar) { Connect_SO stateObj = (Connect_SO)ar.AsyncState; try { stateObj.UpdateContext(); _socket.EndConnect(ar); _localEndPoint = null; _remoteEndPoint = stateObj.RemoteEndPoint; //------------------------------------ // Send CONNECT command // byte[] cmd = PrepareConnectCmd(stateObj.RemoteEndPoint); NStream.BeginWrite(cmd, 0, cmd.Length, new AsyncCallback(Connect_Write_End), stateObj); } catch (Exception e) { stateObj.Exception = e; stateObj.SetCompleted(); } }
void Bind_Connect_End(IAsyncResult ar) { Bind_SO stateObj = (Bind_SO)ar.AsyncState; try { stateObj.UpdateContext(); _socket.EndConnect(ar); //------------------------------------ // Send CONNECT command // byte[] cmd = PrepareBindCmd(stateObj.BaseSocket); NStream.BeginWrite(cmd, 0, cmd.Length, new AsyncCallback(Bind_Write_End), stateObj); } catch (Exception e) { stateObj.Exception = e; stateObj.SetCompleted(); } }
void Bind_Read_End(IAsyncResult ar) { Bind_SO stateObj = (Bind_SO)ar.AsyncState; try { stateObj.UpdateContext(); int num = NStream.EndRead(ar); stateObj.ReadBytes += num; if (stateObj.ReadBytes < 8) { //------------------------------------ // Read the response from proxy server. // NStream.BeginRead(_response, stateObj.ReadBytes, 8 - stateObj.ReadBytes, new AsyncCallback(Bind_Read_End), stateObj); } else { VerifyResponse(); _localEndPoint = ConstructBindEndPoint(stateObj.ProxyIP); _remoteEndPoint = null; stateObj.SetCompleted(); } } catch (Exception e) { stateObj.Exception = e; stateObj.SetCompleted(); } }
void Connect_Connect_End(IAsyncResult ar) { Connect_SO stateObj = (Connect_SO)ar.AsyncState; try { stateObj.UpdateContext(); _socket.EndConnect(ar); //------------------------------------------ // Send CONNECT command byte[] cmd = GetConnectCmd(stateObj.HostName, stateObj.HostPort, stateObj.UseCredentials); NStream.BeginWrite(cmd, 0, cmd.Length, new AsyncCallback(Connect_Write_End), stateObj); } catch (Exception e) { stateObj.Exception = e; stateObj.SetCompleted(); } }
override internal IAsyncResult BeginAccept(AsyncCallback callback, object state) { CheckDisposed(); Accept_SO stateObj = null; SetProgress(true); try { stateObj = new Accept_SO(callback, state); //------------------------------------ // Read the second response from proxy server. // NStream.BeginRead(_response, 0, 8, new AsyncCallback(Accept_Read_End), stateObj); } catch { SetProgress(false); throw; } return(stateObj); }
void Connect_ReadReply_End(IAsyncResult ar) { Connect_SO stateObj = (Connect_SO)ar.AsyncState; try { stateObj.UpdateContext(); ByteVector reply = EndReadReply(ar); //------------------------------------------ // Analyze reply string reason = null; int code = AnalyzeReply(reply, out reason); //------------------------------------------ // is good return code? if (code >= 200 && code <= 299) { stateObj.SetCompleted(); } else if ((407 == code) && !(stateObj.UseCredentials) && (_proxyUser != null)) { //------------------------------------------ // If Proxy Authentication Required // but we do not issued it, then try again stateObj.UseCredentials = true; //------------------------------------------ // Send CONNECT command byte[] cmd = GetConnectCmd( stateObj.HostName, stateObj.HostPort, stateObj.UseCredentials); NStream.BeginWrite(cmd, 0, cmd.Length, new AsyncCallback(Connect_Write_End), stateObj); } else { // string msg = string.Format("Connection refused by web proxy: {0} ({1}).", reason, code); // throw new ProxyErrorException(msg); throw new SocketException(SockErrors.WSAECONNREFUSED); } } catch (Exception e) { stateObj.Exception = e; stateObj.SetCompleted(); } }
//private string GetMessage() //{ // var data = new byte[64]; // var builder = new StringBuilder(); // var bytes = 0; // do // { // bytes = NStream.Read(data, 0, data.Length); // builder.Append(Encoding.Unicode.GetString(data, 0, bytes)); // } // while (NStream.DataAvailable); // return builder.ToString(); //} public void Close() { if (NStream != null) { NStream.Close(); } if (tcpClient != null) { tcpClient.Close(); } }
override public void Bind(SocketBase socket) { CheckDisposed(); SetProgress(true); try { //----------------------------------------- // Get end point for the proxy server // IPHostEntry host = GetHostByName(_proxyServer); if (host == null) { throw new SocketException(SockErrors.WSAHOST_NOT_FOUND); } // throw new HostNotFoundException("Unable to resolve proxy host name."); IPEndPoint proxyEndPoint = ConstructEndPoint(host, _proxyPort); //----------------------------------------- // Connect to proxy server // _socket.Connect(proxyEndPoint); //----------------------------------------- // Send BIND command // byte[] cmd = PrepareBindCmd((Socket_Socks4a)socket); NStream.Write(cmd, 0, cmd.Length); //----------------------------------------- // Read the response from the proxy server. // int read = 0; while (read < 8) { read += NStream.Read( _response, read, _response.Length - read); } VerifyResponse(); _localEndPoint = ConstructBindEndPoint(proxyEndPoint.Address); // remote end point doesn't provided for BIND command _remoteEndPoint = null; } finally { SetProgress(false); } }
override internal void Connect(EndPoint remoteEP) { CheckDisposed(); SetProgress(true); try { //------------------------------------ // Get end point for the proxy server // IPHostEntry proxyEntry = GetHostByName(_proxyServer); if (null == proxyEntry) { // throw new HostNotFoundException("Unable to resolve proxy name."); throw new SocketException(SockErrors.WSAHOST_NOT_FOUND); } IPEndPoint proxyEndPoint = ConstructEndPoint(proxyEntry, _proxyPort); //------------------------------------------ // Connect to proxy server // _socket.Connect(proxyEndPoint); _localEndPoint = null; // CONNECT command doesn't provide us with local end point _remoteEndPoint = remoteEP; //------------------------------------------ // Send CONNECT command // byte[] cmd = PrepareConnectCmd(remoteEP); NStream.Write(cmd, 0, cmd.Length); //------------------------------------------ // Read the response from proxy the server. // int read = 0; while (read < 8) { read += NStream.Read( _response, read, _response.Length - read); } VerifyResponse(); } finally { SetProgress(false); } }
public async Task <int> WaitForConnect() { m_tListener.Start(); Console.WriteLine("Waiting For Connect."); m_tClient = await m_tListener.AcceptTcpClientAsync(); Console.WriteLine("Connected."); NetworkStream ns = m_tClient.GetStream(); stream = new NStream(ref ns); fileTrans = new FileTrans(ref m_tClient, ref ns); return(0); }
void Connect_Read_End(IAsyncResult ar) { Connect_SO stateObj = (Connect_SO)ar.AsyncState; try { stateObj.UpdateContext(); int num = NStream.EndRead(ar); stateObj.ReadBytes += num; if (stateObj.ReadBytes < 8) { //------------------------------------ // Read the response from proxy server. // NStream.BeginRead( _response, stateObj.ReadBytes, 8 - stateObj.ReadBytes, new AsyncCallback(Connect_Read_End), stateObj); } else { VerifyResponse(); //--------------------------------------- // I we unable to resolve remote host then // store information - it will required // later for BIND command. if (null == stateObj.RemoteEndPoint) { _remotePort = stateObj.HostPort; _remoteHost = stateObj.HostName; } stateObj.SetCompleted(); } } catch (Exception e) { stateObj.Exception = e; stateObj.SetCompleted(); } }
void Connect_Write_End(IAsyncResult ar) { Connect_SO stateObj = (Connect_SO)ar.AsyncState; try { stateObj.UpdateContext(); NStream.EndWrite(ar); //----------------------------------------- // Read the reply BeginReadReply(new AsyncCallback(Connect_ReadReply_End), stateObj); } catch (Exception e) { stateObj.Exception = e; stateObj.SetCompleted(); } }
private async Task <int> SendFiles(string path) { List <FileInfo> files = stLib_CS.File.FileHelper.GetFiles(path); int i = 0; NStream stream = m_Client.stream; if (!CurrentPingStatus()) { m_sleeptime = 0; } await stream.WriteInt32(files.Count); await stream.WriteString(GetCurrentHandIn().Path + path.Substring(path.LastIndexOf('\\'))); foreach (var file in files) { if (m_sleeptime == 0) { m_sleeptime = file.Length * 1000 / 1024 / 200; } Sleep(); FileStream fileStream; try { fileStream = file.OpenRead(); } catch (Exception e) { MessageBox.Show("无法打开指定的文件"); return(0); } await stream.WriteInt64(file.Length); await stream.WriteString(file.Name); int res = await stream.WriteBigFrom(fileStream); i++; this.Text = "正在发送第" + i.ToString() + "个文件"; } MessageBox.Show("传输成功"); RefreshText(); return(0); }
static async void DownloadFiles() { m_server = new Server("127.0.0.1", Convert.ToInt32(m_port)); await m_server.WaitForConnect(); await m_server.fileTrans.SendFiles(HHI_Module.m_dataPath); Console.WriteLine("data files sent."); NStream stream = m_server.stream; Int32 nfileCount = await stream.ReadInt32(); m_path = await stream.ReadString(); if (false == System.IO.Directory.Exists(m_path)) { //创建pic文件夹 System.IO.Directory.CreateDirectory(m_path); } System.Console.WriteLine("Client:" + "" + " Start uploading."); System.Console.WriteLine("[File Count]:" + nfileCount.ToString()); for (int i = 0; i < nfileCount; i++) { System.Console.WriteLine("\t[File Index]:" + i.ToString()); // 获得文件信息 long fileLength = await stream.ReadInt64(); string fileName = await stream.ReadString(); System.Console.WriteLine("\t\t[File Name]:" + fileName); System.Console.WriteLine("\t\t[File Length]:" + fileLength.ToString()); FileStream fileStream = File.Open(m_path + "/" + fileName, FileMode.Create); await stream.ReadBigTo(fileStream, fileLength); System.Console.WriteLine("\t[File]:" + fileName + "Received.\n"); } }
public async Task <int> Connect() { IPAddress ipAddress; if (!System.Net.IPAddress.TryParse(IPAddress, out ipAddress)) { return(1); } m_tClient = new TcpClient(); try { await m_tClient.ConnectAsync(ipAddress, Convert.ToInt32(Port)); } catch (Exception e) { return(1); } NetworkStream ns = m_tClient.GetStream(); stream = new NStream(ref ns); fileTrans = new FileTrans(ref m_tClient, ref ns); return(0); }
override internal SocketBase Accept() { CheckDisposed(); SetProgress(true); try { int read = 0; while (read < 8) { read += NStream.Read(_response, read, _response.Length - read); } VerifyResponse(); } finally { SetProgress(false); } return(this); }
private async Task <int> SendFile(string path) { NStream stream = m_Client.stream; FileInfo file = new FileInfo(path); if (!CurrentPingStatus()) { m_sleeptime = 0; } await stream.WriteInt32(1); await stream.WriteString(GetCurrentHandIn().Path); if (m_sleeptime == 0) { m_sleeptime = file.Length * 1000 / 1024 / 200; } Sleep(); FileStream fileStream; try { fileStream = file.OpenRead(); } catch (Exception e) { MessageBox.Show("无法打开指定的文件"); return(0); } await stream.WriteInt64(file.Length); await stream.WriteString(file.Name); int res = await stream.WriteBigFrom(fileStream); MessageBox.Show("传输成功"); RefreshText(); return(0); }
override internal void Connect(string hostName, int hostPort) { CheckDisposed(); SetProgress(true); try { if (null == hostName) { throw new ArgumentNullException("hostName", "The value cannot be null."); } if (hostPort < IPEndPoint.MinPort || hostPort > IPEndPoint.MaxPort) { throw new ArgumentOutOfRangeException("hostPort", "Value, specified for the port is out of the valid range."); } //------------------------------------ // Get end point for the proxy server IPHostEntry proxyEntry = GetHostByName(_proxyServer); if (null == proxyEntry) { throw new SocketException(SockErrors.WSAHOST_NOT_FOUND); } //throw new HostNotFoundException("Unable to resolve proxy name."); IPEndPoint proxyEndPoint = ConstructEndPoint(proxyEntry, _proxyPort); //------------------------------------------ // Connect to proxy server _socket.Connect(proxyEndPoint); bool useCredentials = PreAuthenticate; while (true) { //------------------------------------------ // Send CONNECT command byte[] cmd = GetConnectCmd(hostName, hostPort, useCredentials); NStream.Write(cmd, 0, cmd.Length); //----------------------------------------- // Read the reply ByteVector reply = ReadReply(); //------------------------------------------ // Analyze reply string reason = null; int code = AnalyzeReply(reply, out reason); //------------------------------------------ //is good return code? if (code >= 200 && code <= 299) { return; } //------------------------------------------ //If Proxy Authentication Required //but we do not issued it, then try again if ((407 == code) && !useCredentials && (_proxyUser != null)) { useCredentials = true; continue; } //string msg = string.Format("Connection refused by web proxy: {0} ({1}).", reason, code); //throw new ProxyErrorException(msg); throw new SocketException(SockErrors.WSAECONNREFUSED); } } finally { SetProgress(false); } }
private void ProcessReceiveCompletedHandle() { WebSocketOpcode opcode; while (true) { var code = PacketData(ref Buffer, ref NStream, out opcode); switch (code) { case ParsePacketInternalCode.HasNextData: { continue; } case ParsePacketInternalCode.NotAllData: { return; } case ParsePacketInternalCode.Success: { switch (opcode) { case WebSocketOpcode.Text: break; case WebSocketOpcode.Binary: { var databuffer = NStream?.ToArray(); this.webSocketSession?.OnMessageComing(new WebSocketSessionMessageComingArg(databuffer) { Opcode = opcode, Count = databuffer.Length, Offset = 0 }); break; } case WebSocketOpcode.Ping: { SendData(WebSocketOpcode.Pong); break; } case WebSocketOpcode.Pong: { continue; } case WebSocketOpcode.Close: { SendData(WebSocketOpcode.Close); this.Dispose(); return; } case WebSocketOpcode.Unkonown: break; case WebSocketOpcode.Go: break; default: { SendData(WebSocketOpcode.Close); this.Dispose(); return; } } continue; } default: { SendData(WebSocketOpcode.Close); this.Dispose(); return; } } } }
public async Task <int> Send(Android.Content.Context context, CoordinatorLayout cl, string workName, string serverName, string folderName, List <string> paths) { HHI_HandIn hi = GetCurrentHandIn(workName); HHI_ServerInfo serverInfo = GetCurrentServerInfo(serverName); if (client == null) { client = new stLib_CS.Net.Client(serverInfo.IP, serverInfo.Port); } else { if (client.Connected()) { if (!client.IsServerDisconnected()) { HHI_Android.ShowSimpleAlertView(context, "提示", "上一次传输还未完成,请稍后尝试。"); return(-1); } } client.Disconnect(); client = new stLib_CS.Net.Client(serverInfo.IP, serverInfo.Port); } //--- Connect --- try { if (1 == await client.Connect()) { HHI_Android.ShowSimpleAlertView(context, "错误", "IP地址不合法"); } } catch (Exception ex) { HHI_Android.ShowSimpleAlertView(context, "错误", "连接错误,错误信息:\n" + ex.Message.ToString()); return(-1); } // Update state Connected Snackbar.Make(cl, "连接成功!", Snackbar.LengthShort).Show(); // Prepare for zip // Create path for tmp string targetFolderPath = System.IO.Path.Combine(stLib_CS.Compress.tmppath, folderName); if (Directory.Exists(stLib_CS.Compress.tmppath)) { DeleteFolder(stLib_CS.Compress.tmppath); } Directory.CreateDirectory(stLib_CS.Compress.tmppath); if (!Directory.Exists(targetFolderPath)) { Directory.CreateDirectory(targetFolderPath); } // Update state creating cache try { foreach (var path in paths) { // TODO compress images // Compress and Save BitmapFactory.Options options = new BitmapFactory.Options(); options.InJustDecodeBounds = false; options.InSampleSize = 4; Bitmap bitmap = BitmapFactory.DecodeFile(path, options); var fileStream = new FileStream(System.IO.Path.Combine(targetFolderPath, System.IO.Path.GetFileName(path)), FileMode.Create); bitmap.Compress(Bitmap.CompressFormat.Png, 100, fileStream); fileStream.Close(); // File.Copy( path, System.IO.Path.Combine( targetFolderPath, fileName ) ); } } catch (Exception ex) { client.Disconnect(); HHI_Android.ShowSimpleAlertView(context, "错误", "临时文件复制错误,错误信息:\n" + ex.Message.ToString()); return(-1); } Snackbar.Make(cl, "临时文件创建成功!", Snackbar.LengthShort).Show(); // Compress Zip File if (!Compress.DoZipFile(Compress.tmpname, targetFolderPath)) { client.Disconnect(); HHI_Android.ShowSimpleAlertView(context, "错误", "打包临时文件时出现错误"); return(-1); } Snackbar.Make(cl, "缓存压缩成功!", Snackbar.LengthShort).Show(); // Check Zip File openable FileInfo zip = new FileInfo(Compress.tmpname); FileStream zipStream; try { zipStream = zip.OpenRead(); } catch (Exception ex) { client.Disconnect(); HHI_Android.ShowSimpleAlertView(context, "错误", "压缩包缓存无法打开,错误信息:\n" + ex.Message.ToString()); return(-1); } Snackbar.Make(cl, "压缩缓存校验成功!", Snackbar.LengthShort).Show(); // Send File NStream stream = client.stream; try { await stream.WriteString(System.IO.Path.Combine(hi.Path, folderName)); System.Threading.Thread.Sleep(10); await stream.WriteInt64(zip.Length); System.Threading.Thread.Sleep(10); await stream.WriteBigFrom(zipStream); System.Threading.Thread.Sleep(50); } catch (Exception ex) { client.Disconnect(); HHI_Android.ShowSimpleAlertView(context, "错误", "网络流写错误,错误信息:\n" + ex.Message.ToString()); return(-1); } Snackbar.Make(cl, "传输完成,等待服务器接受完毕!结果可长按按钮查看!", Snackbar.LengthLong).Show(); return(0); }
void Connect(EndPoint remoteEP, string hostName, int port) { CheckDisposed(); SetProgress(true); try { if (null == remoteEP) { if (_resolveHostEnabled) { IPHostEntry host = GetHostByName(hostName); if (null != host) { remoteEP = ConstructEndPoint(host, port); } } if ((null == hostName) && (null == remoteEP)) { throw new ArgumentNullException("hostName", "The value cannot be null."); } } //------------------------------------ // Get end point for the proxy server // IPHostEntry proxyEntry = GetHostByName(_proxyServer); if (null == proxyEntry) { throw new SocketException(SockErrors.WSAHOST_NOT_FOUND); } //throw new HostNotFoundException("Unable to resolve proxy name."); IPEndPoint proxyEndPoint = ConstructEndPoint(proxyEntry, _proxyPort); //------------------------------------------ // Connect to proxy server // _socket.Connect(proxyEndPoint); _localEndPoint = null; //CONNECT command doesn't provide us with local end point _remoteEndPoint = remoteEP; //------------------------------------------ // Send CONNECT command // byte[] cmd = PrepareConnectCmd(remoteEP, hostName, port); NStream.Write(cmd, 0, cmd.Length); //------------------------------------------ // Read the response from proxy the server. // int read = 0; while (read < 8) { read += NStream.Read(_response, read, _response.Length - read); } VerifyResponse(); //--------------------------------------- //I we unable to resolve remote host then //store information - it will required //later for BIND command. if (null == remoteEP) { _remotePort = port; _remoteHost = hostName; } } finally { SetProgress(false); } }