public void ReadCallBack(IAsyncResult ar) { string content = string.Empty; StateObject stateObject = (StateObject)ar.AsyncState; Socket handler = stateObject.workSocket; Data data = new Data(); int bytesRead = handler.EndReceive(ar); if (bytesRead > 0) { content = Encoding.UTF8.GetString(stateObject.buffer, 0, bytesRead); try { MessageModel messageModel = JsonConvert.DeserializeObject <MessageModel>(content); if (messageModel.MessageFile != null) { byte[] filebyte = Convert.FromBase64String(messageModel.MessageFile); string fileName = Guid.NewGuid().ToString(); try { File.WriteAllBytes(this.saveFilePath + fileName + ".png", filebyte); //往指定的路径写入文件 messageModel.MessageFile = fileName; //把文件名插入数据库 } catch (Exception e) { MessageBox.Show("尝试往指定路径写入文件时出错 路径为:" + this.saveFilePath); } PictureBox pictureBox = CreatePicture(filebyte); AddControlToPanel(pictureBox); } if (messageModel.MessageText != null && messageModel.MessageText != "") { Label receivedata = new Label(); receivedata.Text = messageModel.MessageText + " :" + messageModel.CreateTime; receivedata.AutoSize = true; AddControlToPanel(receivedata); } messageModel.Guid = Guid.NewGuid().ToString(); bool result = data.InsertMessage(messageModel); Send(handler, messageModel);//返回信息 if (!result) { MessageBox.Show("Insert Message Error"); } } catch (Exception e) { MessageBox.Show("receive error" + e.ToString()); } } }