private async void DownLoadBigPic(DetailMovie dm) { HttpStatusCode sc = HttpStatusCode.Forbidden; if (dm.bigimageurl != "") { (bool success, string cookie) = await Task.Run(() => { return(MyNet.DownLoadImage(dm.bigimageurl, ImageType.BigImage, dm.id, callback: (statuscode) => { sc = (HttpStatusCode)statuscode; })); }); if (success) { BigImageDownLoadCompleted?.Invoke(this, new MessageCallBackEventArgs(dm.id)); } else { MessageCallBack?.Invoke(this, new MessageCallBackEventArgs($"{Jvedio.Language.Resources.DownloadBPicFailFor} {sc.ToStatusMessage()} {Jvedio.Language.Resources.Message_ViewLog}")); } } InfoUpdate?.Invoke(this, new DetailMovieEventArgs() { DetailMovie = dm, value = Value, maximum = Maximum }); }
public virtual void Dispose() { m_messageCallBack = null; m_socketService.Dispose(); m_socketService = null; }
public void RegistMessage(string szProtoName, MessageCallBack pfCallBack) { if (m_mapCallBack.ContainsKey(szProtoName)) { H5Helper.H5AlertString("already registed proto " + szProtoName); return; } m_mapCallBack[szProtoName] = pfCallBack; }
/// <summary> /// 添加服务 /// </summary> /// <param name="service">服务</param> public static void AddService(BaseService service) { if (m_messageCallBack == null) { m_messageCallBack = new MessageCallBack(CallBack); RegisterCallBack(m_messageCallBack); } m_services[service.ServiceID] = service; }
public int RegisterMessageCallbackOrderly(MessageCallBack callback) { var pCallback = new ConsumerNativeMethodsDelegate.PtrMessageCallBack((consumer, message) => { var code = callback(new MessageReader(this._functionLoader, message)); // TODO: release message ptr. return(code); }); return(this._functionLoader.LoadFunction <ConsumerNativeMethodsDelegate.RegisterMessageCallbackOrderly>(nameof(RegisterMessageCallbackOrderly))(this._pushConsumerHandle, pCallback)); }
public async void DownLoad() { IsDownLoading = true; //下载信息 if (DetailMovie.IsToDownLoadInfo()) { HttpResult httpResult = await Net.DownLoadFromNet(DetailMovie); if (httpResult != null) { if (!httpResult.Success) { string error = httpResult.Error != "" ? httpResult.Error : httpResult.StatusCode.ToStatusMessage(); MessageCallBack?.Invoke(this, new MessageCallBackEventArgs($" {DetailMovie.id} {Jvedio.Language.Resources.DownloadMessageFailFor}:{error}")); } } } DetailMovie dm = new DetailMovie(); dm = DataBase.SelectDetailMovieById(DetailMovie.id); if (string.IsNullOrEmpty(dm.title)) { InfoUpdate?.Invoke(this, new DetailMovieEventArgs() { DetailMovie = dm, value = 1, maximum = 1 }); return; } InfoUpdate?.Invoke(this, new DetailMovieEventArgs() { DetailMovie = dm, value = Value, maximum = Maximum }); InfoDownloadCompleted?.Invoke(this, new MessageCallBackEventArgs(DetailMovie.id)); if (!File.Exists(BasePicPath + $"BigPic\\{dm.id}.jpg")) { DownLoadBigPic(dm); //下载大图 } if (!File.Exists(BasePicPath + $"SmallPic\\{dm.id}.jpg")) { DownLoadSmallPic(dm); //下载小图 } List <string> urlList = new List <string>(); foreach (var item in dm.extraimageurl?.Split(';')) { if (!string.IsNullOrEmpty(item)) { urlList.Add(item); } } Maximum = urlList.Count() == 0 ? 1 : urlList.Count; DownLoadExtraPic(dm);//下载预览图 }
public void Register(object token, MessageCallBack msg) { if (m_msgDict.ContainsKey(msg)) { m_msgDict[token] += msg; } else { m_msgDict[token] = msg; } }
public void Unregister(object token, MessageCallBack msg) { if (m_msgDict.ContainsKey(token)) { m_msgDict[token] -= msg; if (m_msgDict[token] == null) { m_msgDict.Remove(token); } } }
/// <summary> /// SharingServiceからメッセージを受信したときのハンドラ /// メッセージタイプ(TestMessageIDのいずれか)に対応させるハンドラを決定する /// </summary> /// <param name="connection"></param> /// <param name="msg"></param> private void OnMessageReceived(NetworkConnection connection, NetworkInMessage msg) { // メッセージタイプの取り出し byte messageType = msg.ReadByte(); // 対応させるハンドラの決定してコール MessageCallBack messageHandler = MessageHandlers[(TestMessageID)messageType]; if (messageHandler != null) { messageHandler(msg); } }
/// <summary> /// 添加服务 /// </summary> /// <param name="service">服务</param> public static void AddService(BaseService service) { if (m_messageCallBack == null) { m_messageCallBack = new MessageCallBack(CallBack); RegisterCallBack(m_messageCallBack); m_writeLogCallBack = new WriteLogCallBack(WriteServerLog); RegisterLog(m_writeLogCallBack); } lock (m_services) { m_services.Add(service); } }
private async void DownLoadExtraPic(DetailMovie dm) { List <string> urlList = dm.extraimageurl?.Split(';').Where(arg => arg.IsProperUrl()).ToList(); bool dlimageSuccess = false; string cookies = ""; for (int i = 0; i < urlList.Count(); i++) { HttpStatusCode sc = HttpStatusCode.Forbidden; if (cts.IsCancellationRequested) { CancelEvent?.Invoke(this, EventArgs.Empty); break; } string filepath = ""; filepath = BasePicPath + "ExtraPic\\" + dm.id + "\\" + Path.GetFileName(new Uri(urlList[i]).LocalPath); if (!File.Exists(filepath)) { (dlimageSuccess, cookies) = await Task.Run(() => { return(MyNet.DownLoadImage(urlList[i], ImageType.ExtraImage, dm.id, Cookie: cookies, callback: (statuscode) => { sc = (HttpStatusCode)statuscode; })); }); if (dlimageSuccess) { ExtraImageDownLoadCompleted?.Invoke(this, new MessageCallBackEventArgs(filepath)); if (urlList[i].IndexOf("dmm") > 0) { Thread.Sleep(Delay.MEDIUM); } else { Thread.Sleep(Delay.SHORT_3); } } else { Logger.LogN($" {Jvedio.Language.Resources.Preview} {i + 1} {Jvedio.Language.Resources.Message_Fail}:{urlList[i]}, {Jvedio.Language.Resources.Reason} : {sc.ToStatusMessage()}"); MessageCallBack?.Invoke(this, new MessageCallBackEventArgs($" {Jvedio.Language.Resources.Preview} {i + 1} {Jvedio.Language.Resources.Message_Fail},{Jvedio.Language.Resources.Reason} :{sc.ToStatusMessage()} ,{Jvedio.Language.Resources.Message_ViewLog}")); } } lock (lockobject) Value += 1; InfoUpdate?.Invoke(this, new DetailMovieEventArgs() { DetailMovie = dm, value = Value, maximum = Maximum }); } lock (lockobject) Value = Maximum; InfoUpdate?.Invoke(this, new DetailMovieEventArgs() { DetailMovie = dm, value = Value, maximum = Maximum }); IsDownLoading = false; }
/// <summary> /// 回传消息,如果回传失败会打印到控制台 /// </summary> /// <param name="messageCallBack"></param> /// <param name="token"></param> /// <param name="message"></param> /// <param name="code"></param> private void SetMessage(MessageCallBack messageCallBack, string token, string message, int code) { if (null != message) { try { messageCallBack(token, message, code); } catch (System.Exception ex) { Console.WriteLine(string.Format("token:{0},code:{1},message:{2},exception:{3}", token, code, message, ex.Message)); } } Console.WriteLine(string.Format("token:{0},code:{1},message:{2}", token, code, message)); }
/// <summary> /// 添加服务 /// </summary> /// <param name="service">服务</param> public static void AddService(BaseService service) { if (m_messageCallBack == null) { try { m_messageCallBack = new MessageCallBack(CallBack); RegisterCallBack(m_messageCallBack); m_writeLogCallBack = new WriteLogCallBack(WriteServerLog); RegisterLog(m_writeLogCallBack); } catch (Exception ex) { } } m_services[service.ServiceID] = service; }
/// <summary> /// 从服务接受信息 /// </summary> /// <param name="msgInterface"></param> public void ReciverFromServerMsg(IMsgInterface msgInterface) { try { foreach (var item in msgInterface.MsgInfos) { //if(item.Value.MessageType == InterfaceLib.MsgInterface.MsgInfo.Enums.MessageType.File) //{ // Log.Write("FileMessage", item.Value.SendId); //} MessageCallBack?.Invoke(item.Value); } } catch (Exception ex) { Log.Write(ex); } }
private async void DownLoadSmallPic(DetailMovie dm) { HttpStatusCode sc = HttpStatusCode.Forbidden; if (dm.smallimageurl != "") { (bool success, string cookie) = await Task.Run(() => { return(MyNet.DownLoadImage(dm.smallimageurl, ImageType.SmallImage, dm.id, callback: (statuscode) => { sc = (HttpStatusCode)statuscode; })); }); if (success) { SmallImageDownLoadCompleted?.Invoke(this, new MessageCallBackEventArgs(dm.id)); } else { MessageCallBack?.Invoke(this, new MessageCallBackEventArgs($"{Jvedio.Language.Resources.DownloadSPicFailFor} {sc.ToStatusMessage()} {Jvedio.Language.Resources.Message_ViewLog}")); } } }
public extern static void RegisterCallBack(MessageCallBack callBack);
private async void DownLoad(object o) { //下载信息 Movie movie = o as Movie; if (movie.id.ToUpper().StartsWith("FC2")) { SemaphoreFC2.WaitOne(); } else { Semaphore.WaitOne();//阻塞 } if (Cancel || string.IsNullOrEmpty(movie.id)) { if (movie.id.ToUpper().StartsWith("FC2")) { SemaphoreFC2.Release(); } else { Semaphore.Release(); } return; } //下载信息 State = DownLoadState.DownLoading; if (movie.IsToDownLoadInfo() || enforce) { //满足一定条件才下载信息 HttpResult httpResult = await Net.DownLoadFromNet(movie); if (httpResult != null) { if (httpResult.Success) { InfoUpdate?.Invoke(this, new InfoUpdateEventArgs() { Movie = movie, progress = downLoadProgress.value, Success = httpResult.Success }); //委托到主界面显示 } else { string error = httpResult.Error != "" ? httpResult.Error : httpResult.StatusCode.ToStatusMessage(); MessageCallBack?.Invoke(this, new MessageCallBackEventArgs($" {movie.id} {Jvedio.Language.Resources.DownloadMessageFailFor}:{error}")); } } } DetailMovie dm = DataBase.SelectDetailMovieById(movie.id); if (dm == null) { if (movie.id.ToUpper().StartsWith("FC2")) { SemaphoreFC2.Release(); } else { Semaphore.Release(); } return; } if (!File.Exists(BasePicPath + $"BigPic\\{dm.id}.jpg") || enforce) { await Net.DownLoadImage(dm.bigimageurl, ImageType.BigImage, dm.id);//下载大图 } //fc2 没有缩略图 if (dm.id.IndexOf("FC2") >= 0) { //复制海报图作为缩略图 if (File.Exists(BasePicPath + $"BigPic\\{dm.id}.jpg") && !File.Exists(BasePicPath + $"SmallPic\\{dm.id}.jpg")) { try { File.Copy(BasePicPath + $"BigPic\\{dm.id}.jpg", BasePicPath + $"SmallPic\\{dm.id}.jpg"); } catch (Exception ex) { Logger.LogF(ex); } } } else { if (!File.Exists(BasePicPath + $"SmallPic\\{dm.id}.jpg") || enforce) { await Net.DownLoadImage(dm.smallimageurl, ImageType.SmallImage, dm.id); //下载小图 } } dm.smallimage = ImageProcess.GetBitmapImage(dm.id, "SmallPic"); InfoUpdate?.Invoke(this, new InfoUpdateEventArgs() { Movie = dm, progress = downLoadProgress.value, state = State }); //委托到主界面显示 dm.bigimage = ImageProcess.GetBitmapImage(dm.id, "BigPic"); lock (downLoadProgress.lockobject) downLoadProgress.value += 1; //完全下载完一个影片 InfoUpdate?.Invoke(this, new InfoUpdateEventArgs() { Movie = dm, progress = downLoadProgress.value, state = State, Success = true }); //委托到主界面显示 Task.Delay(DelayInvterval).Wait(); //每个线程之间暂停 //取消阻塞 if (movie.id.ToUpper().IndexOf("FC2") >= 0) { SemaphoreFC2.Release(); } else { Semaphore.Release(); } }
private async void DownLoad(object o) { Semaphore.WaitOne(); Actress actress = o as Actress; if (Cancel | actress.id == "") { Semaphore.Release(); return; } try { this.State = DownLoadState.DownLoading; //下载头像 if (!string.IsNullOrEmpty(actress.imageurl)) { string url = actress.imageurl; HttpResult streamResult = await Net.DownLoadFile(url); if (streamResult != null) { ImageProcess.SaveImage(actress.name, streamResult.FileByte, ImageType.ActorImage, url); actress.smallimage = ImageProcess.GetBitmapImage(actress.name, "Actresses"); } } //下载信息 bool success = false; success = await Task.Run(() => { Task.Delay(300).Wait(); return(Net.DownLoadActress(actress.id, actress.name, callback: (message) => { MessageCallBack?.Invoke(this, new MessageCallBackEventArgs(message)); })); }); if (success) { actress = DataBase.SelectInfoByActress(actress); } ProgressBarUpdate.value += 1; InfoUpdate?.Invoke(this, new ActressUpdateEventArgs() { Actress = actress, progressBarUpdate = ProgressBarUpdate, state = State }); } catch (Exception ex) { Console.WriteLine(ex.Message); } finally { Semaphore.Release(); } }
private static extern void CLIENT_SetDVRMessCallBack(MessageCallBack cb, IntPtr dwUser);
/// <summary> /// 提交同步Post请求 /// 具体参数参考:HttpRequest 方法 /// </summary> /// <param name="url">请求地址</param> /// <param name="token"></param> /// <param name="requestPre"></param> /// <param name="requestWrite"></param> /// <param name="responseRead"></param> /// <param name="message"></param> /// <returns></returns> public bool HttpPostRequest(string url, string token, RequestPreCallBack requestPre, RequestWriteCallBack requestWrite, ResponseReadCallBack responseRead, MessageCallBack message) { return HttpRequest(url, token, Post, -1, requestPre, requestWrite, responseRead, message); }
/// <summary> /// 日志回调 /// </summary> /// <param name="obj"></param> private void LogInfo_ErroStringEvent(LogMessage obj) { MessageCallBack?.Invoke(obj); }
public static extern int RegisterMessageCallback( IntPtr consumer, [MarshalAs(UnmanagedType.FunctionPtr)] MessageCallBack pCallback );
/// <summary> /// 提交异步Post请求 /// 具体参数参考:HttpRequest 方法 /// </summary> /// <param name="url">请求地址</param> /// <param name="token"></param> /// <param name="requestPre"></param> /// <param name="requestWrite"></param> /// <param name="responseRead"></param> /// <param name="message"></param> public void HttpPostRequestAsync(string url, string token, RequestPreCallBack requestPre, RequestWriteCallBack requestWrite, ResponseReadCallBack responseRead, MessageCallBack message) { new Thread(new ThreadStart( delegate { HttpPostRequest(url, token, requestPre, requestWrite, responseRead, message); } )).Start(); }
public static extern bool NET_DVR_SetDVRMessageCallBack(MessageCallBack fMessageCallBack, uint dwUser);
/// <summary> /// 提交异步Post请求 /// 具体参数参考:HttpRequest 方法 /// </summary> /// <param name="url">请求地址</param> /// <param name="token"></param> /// <param name="requestPre"></param> /// <param name="requestWrite"></param> /// <param name="responseRead"></param> /// <param name="message"></param> public void HttpPostRequestAsync(string url, string token, RequestPreCallBack requestPre, RequestWriteCallBack requestWrite, ResponseReadCallBack responseRead, MessageCallBack message) { new Thread(new ThreadStart( delegate { HttpPostRequest(url, token, requestPre, requestWrite, responseRead, message); } )).Start(); }
/// <summary> /// 进行Http交互 /// </summary> /// <param name="url">请求地址</param> /// <param name="token">令牌</param> /// <param name="method">请求方式:POST、GET</param> /// <param name="contentLength">当为 -1 时,不设定 ContentLength</param> /// <param name="requestPre">请求之前回调</param> /// <param name="requestWrite">输入流回调</param> /// <param name="responseRead">输出流回调</param> /// <param name="message">消息回调</param> /// <returns></returns> private bool HttpRequest(string url, string token, string method, long contentLength, RequestPreCallBack requestPre, RequestWriteCallBack requestWrite, ResponseReadCallBack responseRead, MessageCallBack message) { if (string.IsNullOrEmpty(url)) { this.SetMessage(message, token, "请求的地址为空", 0); return(false); } HttpWebRequest request = null; Stream streamRequest = null; HttpWebResponse response = null; Stream streamResponse = null; string http = "http://"; string host = url; string port = "80"; string path = url; if (url.ToLower().StartsWith("http")) { http = url.Substring(0, url.IndexOf(':')) + "://"; host = url.Substring(url.IndexOf(':') + 3); path = host; } int pos = -1; if ((pos = host.IndexOf('/')) != -1) { host = host.Substring(0, pos); path = path.Substring(pos); } else if ((pos = host.IndexOf('?')) != -1) { host = host.Substring(0, pos); path = path.Substring(pos); } else { path = ""; } if ((pos = host.IndexOf(":")) != -1) { port = host.Substring(pos + 1); host = host.Substring(0, pos); } try { this.SetMessage(message, token, "正在连接网络...", 1); request = (HttpWebRequest)WebRequest.Create(url); request.ProtocolVersion = HttpVersion.Version11; request.Accept = "*/*"; request.Headers.Add("Accept-Language", "zh-cn"); request.Headers.Add("UA-OS", "Windows CE (Pocket PC)"); request.Referer = null; request.Headers.Add("Accept-Encoding", "gzip,deflate"); request.UserAgent = "Mozilla/4.0 (compatible; MSIE 6.0; Windows CE; IEMobile 6.12) - Beluga BeefWrapNet 1.0"; request.KeepAlive = true; request.AllowAutoRedirect = true; request.MaximumAutomaticRedirections = 3; // request.Credentials = CredentialCache.DefaultCredentials; // request.ContentType = "text/html"; // request.Headers.Add("Pragma", "no-cache"); // request.Headers.Add("cache-control", "no-store, no-cache, must-revalidate, post-check=0, pre-check=0"); request.Timeout = 30 * 1000; // 超时时间 60 秒 string cookies = GetCookies(host + ":" + port); if (!string.IsNullOrEmpty(cookies)) { request.Headers.Add("Cookie", cookies); } if (string.IsNullOrEmpty(method) || string.IsNullOrEmpty(method.Trim())) { request.Method = Post; } else { request.Method = method; } if (!string.IsNullOrEmpty(request.Method) && request.Method.Trim().ToLower().Equals(Post.ToLower())) { request.ContentType = "application/x-www-form-urlencoded"; if (contentLength >= 0) { request.ContentLength = contentLength; request.SendChunked = false; } else { request.SendChunked = true; } } if (null != requestPre) { requestPre(token, request); } this.SetMessage(message, token, "正在连接服务器...", 2); // 发送数据 if (null != requestWrite) { streamRequest = request.GetRequestStream(); this.SetMessage(message, token, "连接成功,正在请求数据...", 3); requestWrite(token, ref streamRequest); streamRequest.Flush(); streamRequest.Close(); streamRequest = null; } // 接收数据 response = (HttpWebResponse)request.GetResponse(); SetCookies(host, response.Headers.GetValues("Set-Cookie")); if (null != responseRead) { this.SetMessage(message, token, "已收到数据:", 4); streamResponse = response.GetResponseStream(); responseRead(token, ref streamResponse, response); } this.SetMessage(message, token, "完成", 0); return(true); } catch (Exception ex) { this.SetMessage(message, token, "网络故障:" + ex.Message, -1); } finally { if (null != response) { try { response.Close(); } catch { } response = null; } if (null != request) { try { request.Abort(); } catch { } request = null; } } return(false); }
/// <summary> /// 提交同步Get请求 /// 具体参数参考:HttpRequest 方法 /// </summary> /// <param name="url">请求地址</param> /// <param name="token"></param> /// <param name="requestPre"></param> /// <param name="requestWrite"></param> /// <param name="responseRead"></param> /// <param name="message"></param> /// <returns></returns> public bool HttpGetRequest(string url, string token, RequestPreCallBack requestPre, RequestWriteCallBack requestWrite, ResponseReadCallBack responseRead, MessageCallBack message) { return(HttpRequest(url, token, Get, -1, requestPre, requestWrite, responseRead, message)); }
private async void DownLoad(object o) { //下载信息=>下载图片 Movie movie = o as Movie; if (movie.id.ToUpper().StartsWith("FC2")) { SemaphoreFC2.WaitOne(); } else { Semaphore.WaitOne(); //阻塞 } if (Cancel || string.IsNullOrEmpty(movie.id)) { if (movie.id.ToUpper().StartsWith("FC2")) { SemaphoreFC2.Release(); } else { Semaphore.Release(); } return; } bool success; string resultMessage; //下载信息 State = DownLoadState.DownLoading; if (Net.IsToDownLoadInfo(movie) || enforce) { //满足一定条件才下载信息 (success, resultMessage) = await Task.Run(() => { return(Net.DownLoadFromNet(movie)); }); InfoUpdate?.Invoke(this, new InfoUpdateEventArgs() { Movie = movie, progress = downLoadProgress.value, Success = success }); //委托到主界面显示 if (!success) { MessageCallBack?.Invoke(this, new MessageCallBackEventArgs($" {movie.id} {Jvedio.Language.Resources.DownloadMessageFailFor}:{(resultMessage.ToStatusMessage())}")); } } DetailMovie dm = new DetailMovie(); dm = DataBase.SelectDetailMovieById(movie.id); if (!File.Exists(BasePicPath + $"BigPic\\{dm.id}.jpg") || enforce) { string message2 = ""; (bool success2, string cookie2) = await Net.DownLoadImage(dm.bigimageurl, ImageType.BigImage, dm.id, callback : (sc) => { message2 = sc.ToString(); });//下载大图 //if (!success2) MessageCallBack?.Invoke(this, new MessageCallBackEventArgs($" {dm.id} 海报图下载失败,原因:{message2.ToStatusMessage()}")); } //fc2 没有缩略图 if (dm.id.IndexOf("FC2") >= 0) { //复制海报图作为缩略图 if (File.Exists(BasePicPath + $"BigPic\\{dm.id}.jpg") && !File.Exists(BasePicPath + $"SmallPic\\{dm.id}.jpg")) { File.Copy(BasePicPath + $"BigPic\\{dm.id}.jpg", BasePicPath + $"SmallPic\\{dm.id}.jpg"); } } else { if (!File.Exists(BasePicPath + $"SmallPic\\{dm.id}.jpg") || enforce) { string message = ""; (bool success1, string cookie) = await Net.DownLoadImage(dm.smallimageurl, ImageType.SmallImage, dm.id, callback : (sc) => { message = sc.ToString(); }); //下载小图 //if (!success1) MessageCallBack?.Invoke(this, new MessageCallBackEventArgs($" {dm.id} 缩略图下载失败,原因:{message.ToStatusMessage()}")); } } dm.smallimage = ImageProcess.GetBitmapImage(dm.id, "SmallPic"); InfoUpdate?.Invoke(this, new InfoUpdateEventArgs() { Movie = dm, progress = downLoadProgress.value, state = State }); //委托到主界面显示 dm.bigimage = ImageProcess.GetBitmapImage(dm.id, "BigPic"); lock (downLoadProgress.lockobject) downLoadProgress.value += 1; //完全下载完一个影片 InfoUpdate?.Invoke(this, new InfoUpdateEventArgs() { Movie = dm, progress = downLoadProgress.value, state = State, Success = true }); //委托到主界面显示 Task.Delay(DelayInvterval).Wait(); //每个线程之间暂停 //取消阻塞 if (movie.id.ToUpper().IndexOf("FC2") >= 0) { SemaphoreFC2.Release(); } else { Semaphore.Release(); } }
/// <summary> /// 提交同步Post请求 /// 具体参数参考:HttpRequest 方法 /// </summary> /// <param name="url">请求地址</param> /// <param name="token"></param> /// <param name="contentLength"></param> /// <param name="requestPre"></param> /// <param name="requestWrite"></param> /// <param name="responseRead"></param> /// <param name="message"></param> /// <returns></returns> public bool HttpPostRequest(string url, string token, int contentLength, RequestPreCallBack requestPre, RequestWriteCallBack requestWrite, ResponseReadCallBack responseRead, MessageCallBack message) { return(HttpRequest(url, token, Post, contentLength, requestPre, requestWrite, responseRead, message)); }
/// <summary> /// 进行Http交互 /// </summary> /// <param name="url">请求地址</param> /// <param name="token">令牌</param> /// <param name="method">请求方式:POST、GET</param> /// <param name="contentLength">当为 -1 时,不设定 ContentLength</param> /// <param name="requestPre">请求之前回调</param> /// <param name="requestWrite">输入流回调</param> /// <param name="responseRead">输出流回调</param> /// <param name="message">消息回调</param> /// <returns></returns> private bool HttpRequest(string url, string token, string method, long contentLength, RequestPreCallBack requestPre, RequestWriteCallBack requestWrite, ResponseReadCallBack responseRead, MessageCallBack message) { if (string.IsNullOrEmpty(url)) { this.SetMessage(message, token, "请求的地址为空", 0); return false; } HttpWebRequest request = null; Stream streamRequest = null; HttpWebResponse response = null; Stream streamResponse = null; string http = "http://"; string host = url; string port = "80"; string path = url; if (url.ToLower().StartsWith("http")) { http = url.Substring(0, url.IndexOf(':')) + "://"; host = url.Substring(url.IndexOf(':') + 3); path = host; } int pos = -1; if ((pos = host.IndexOf('/')) != -1) { host = host.Substring(0, pos); path = path.Substring(pos); } else if ((pos = host.IndexOf('?')) != -1) { host = host.Substring(0, pos); path = path.Substring(pos); } else { path = ""; } if ((pos = host.IndexOf(":")) != -1) { port = host.Substring(pos + 1); host = host.Substring(0, pos); } try { this.SetMessage(message, token, "正在连接网络...", 1); request = (HttpWebRequest)WebRequest.Create(url); request.ProtocolVersion = HttpVersion.Version11; request.Accept = "*/*"; request.Headers.Add("Accept-Language", "zh-cn"); request.Headers.Add("UA-OS", "Windows CE (Pocket PC)"); request.Referer = null; request.Headers.Add("Accept-Encoding", "gzip,deflate"); request.UserAgent = "Mozilla/4.0 (compatible; MSIE 6.0; Windows CE; IEMobile 6.12) - Beluga BeefWrapNet 1.0"; request.KeepAlive = true; request.AllowAutoRedirect = true; request.MaximumAutomaticRedirections = 3; // request.Credentials = CredentialCache.DefaultCredentials; // request.ContentType = "text/html"; // request.Headers.Add("Pragma", "no-cache"); // request.Headers.Add("cache-control", "no-store, no-cache, must-revalidate, post-check=0, pre-check=0"); request.Timeout = 30 * 1000; // 超时时间 60 秒 string cookies = GetCookies(host + ":" + port); if (!string.IsNullOrEmpty(cookies)) { request.Headers.Add("Cookie", cookies); } if (string.IsNullOrEmpty(method) || string.IsNullOrEmpty(method.Trim())) { request.Method = Post; } else { request.Method = method; } if (!string.IsNullOrEmpty(request.Method) && request.Method.Trim().ToLower().Equals(Post.ToLower())) { request.ContentType = "application/x-www-form-urlencoded"; if (contentLength >= 0) { request.ContentLength = contentLength; request.SendChunked = false; } else { request.SendChunked = true; } } if (null != requestPre) { requestPre(token, request); } this.SetMessage(message, token, "正在连接服务器...", 2); // 发送数据 if (null != requestWrite) { streamRequest = request.GetRequestStream(); this.SetMessage(message, token, "连接成功,正在请求数据...", 3); requestWrite(token, ref streamRequest); streamRequest.Flush(); streamRequest.Close(); streamRequest = null; } // 接收数据 response = (HttpWebResponse)request.GetResponse(); SetCookies(host, response.Headers.GetValues("Set-Cookie")); if (null != responseRead) { this.SetMessage(message, token, "已收到数据:", 4); streamResponse = response.GetResponseStream(); responseRead(token, ref streamResponse, response); } this.SetMessage(message, token, "完成", 0); return true; } catch (Exception ex) { this.SetMessage(message, token, "网络故障:" + ex.Message, -1); } finally { if (null != response) { try { response.Close(); } catch { } response = null; } if (null != request) { try { request.Abort(); } catch { } request = null; } } return false; }
/// <summary> /// 回传消息,如果回传失败会打印到控制台 /// </summary> /// <param name="messageCallBack"></param> /// <param name="token"></param> /// <param name="message"></param> /// <param name="code"></param> private void SetMessage(MessageCallBack messageCallBack, string token, string message, int code) { if (null != message) { try { messageCallBack(token, message, code); } catch (System.Exception ex) { Console.WriteLine(string.Format("token:{0},code:{1},message:{2},exception:{3}", token, code, message, ex.Message)); } } Console.WriteLine(string.Format("token:{0},code:{1},message:{2}", token, code, message)); }
/// <summary> /// 提交同步Get请求 /// 具体参数参考:HttpRequest 方法 /// </summary> /// <param name="url">请求地址</param> /// <param name="token"></param> /// <param name="contentLength"></param> /// <param name="rquestPre"></param> /// <param name="requestWrite"></param> /// <param name="responseRead"></param> /// <param name="message"></param> /// <returns></returns> public bool HttpGetRequest(string url, string token, int contentLength, RequestPreCallBack rquestPre, RequestWriteCallBack requestWrite, ResponseReadCallBack responseRead, MessageCallBack message) { return HttpRequest(url, token, Get, contentLength, rquestPre, requestWrite, responseRead, message); }
public LocalClient(string tName, MessageCallBack tOnMsg, ServicesCore tBase) : base(tName, tBase) { Cmds = new CommandList(); OnMsg = tOnMsg; }