C#用Socket异步时出现错误

各位大侠:
我刚用 C# 写Socket 代码,服务器端用异步监控客户端,代码如下
//开启服务器端监控---Begin
internal void MonitorClient()
{
IPEndPoint ipep = new IPEndPoint(IPAddress.Any, 端口号);
Socket serverSocket = new Socket(ipep.AddressFamily, SocketType.Stream, ProtocolType.Tcp);
try
{
serverSocket.Bind(ipep);
serverSocket.Listen(100);
serverSocket.BeginAccept(clientAcceptCallBack, serverSocket);
}
catch ( }
finally { } //serverSocket.Close(); serverSocket.Dispose();
}//End

    //异步监听客户端连接---Begin
    private void clientAcceptCallBack(IAsyncResult ar)
    {
        string IP     = "";
        try
        {
            Socket serverSocket = ar.AsyncState as Socket;
            Socket clientSocket = serverSocket.EndAccept(ar);     //结束异步Accept并获已连接的Socket
            IPEndPoint ipEndPoint = (IPEndPoint)clientSocket.RemoteEndPoint; //可能在这里或上面两行出错
            IP = ipEndPoint.Address.ToString() + ":" + ipEndPoint.Port.ToString();               
            ThreadPool.QueueUserWorkItem(new WaitCallback(acceptClientMsg), (object)IP);   //收信息,并根据收到的信息执行相关操作
            serverSocket.BeginAccept(clientAcceptCallBack, serverSocket); //继续异步Accept,保持Accept一直开启! 
        }
        catch (Exception ex) { }
        finally { }
    }//End


            在 clientAcceptCallBack 中偶尔会出现“远程主机关闭了一个现有连接”的错误,但出现次数少,没办法跟踪。

            由于出现次数少,没有规律,目前还不知道具体是什么原因,没办法跟踪和解决。

            有没有哪位高手知道是什么原因,或碰到过?
c#

2个回答

acceptClientMsg 里是如何处理的?接收到消息后是否有返回信息?
如果有的话,应该是服务器端处理时间常,客户端ACCEPT超时,自动断开连接了。然后服务器端处理完毕后发送信息的时候就会出现已经关闭的错误。
不知道是不是这个问题,可以在ThreadPool.QueueUserWorkItem(new WaitCallback(acceptClientMsg), (object)IP); 之前加SLEEP,看看是否会固定出现关闭的错误。

acceptClientMsg 专门负责处理消息,根据消息的类型执行各种操作,有些会返回信息给客户端,有些不会。我原来用 .exe 运行,当时发现:一般在客户端连接或断开的时候经常会出现这种情况。遗憾的是我用代码运行服务器后就没有出现这种情况。
谢谢 houwhf,我先按你说的改下程序。

Csdn user default icon
上传中...
上传图片
插入图片
抄袭、复制答案,以达到刷声望分或其他目的的行为,在CSDN问答是严格禁止的,一经发现立刻封号。是时候展现真正的技术了!
其他相关推荐
c#客户端程序 socket异步接收终端设备传输的数据

现在要做一个客户端程序,需要接收终端设备传输过来的数据,需要做到多线程异步通讯,求大神解决

Socket异步通讯,瞬间开启多个异步

![图片说明](https://img-ask.csdn.net/upload/201907/27/1564195208_663259.png) 请问网络流瞬间开启多个异步(比如1、2、3),那么那么服务器端收到的顺序是否会乱掉(可能收到的顺序不是1、2、3)? 如果异步发送 BeginWrite() 换成同步发送 Write() 呢?

c#的异步socket回调是多线程回调,怎么处理的

在写一个unity的项目网络层,用c#的异步socket,BeginSend,EndSend,BeginReceive,EndReceive,但是发现回调的方式是多线程回调: 下面的代码我在回调的地方打印出线程id,发现不一样: 如果是多线程回调,那么收到数据recve回调的时候想要做包解析,必须要自己把这个事件丢到消息队列中放到网络层线程中去处理,这样又好麻烦,感觉这个异步的接口应该不会这么麻烦吧,怀疑是不是用错了。有没有遇到相同问题的,求教一下怎么处理的。 /// 异步发送 public void AsynSend() { if (m_socket == null) return; //编码 try { m_socket.BeginSend(m_sendBuffer, 0, m_sendPos, SocketFlags.None, asyncResult => { //完成发送消息 int bytes = m_socket.EndSend(asyncResult); if(bytes <= 0) { Close(); return; } UnityEngine.Debug.LogWarning("send length:"+bytes); UnityEngine.Debug.LogWarning("current send thread:" + Thread.CurrentThread.ManagedThreadId); m_sendPos -= bytes; }, null); } catch (Exception ex) { Close(); UnityEngine.Debug.LogWarning("异常信息:"+ ex.Message); } } //异步接受 public void AsynRecive() { try { //开始接收数据 m_socket.BeginReceive(m_recvBuffer, m_recvPos, m_recvBuffer.Length - m_recvPos, SocketFlags.None, asyncResult => { int bytes = m_socket.EndReceive(asyncResult); UnityEngine.Debug.LogWarning("recv length:"+bytes); UnityEngine.Debug.LogWarning("current recv thread:" + Thread.CurrentThread.ManagedThreadId); AsynRecive(); if (bytes <= 0) { Close(); return; } m_recvPos += bytes; ParseProtocol(); }, null); } catch (Exception ex) { Close(); UnityEngine.Debug.LogWarning("异常信息:"+ex.Message); } }

c# socket同步操作代码改异步操作,客户端界面错误问题

c# socket同步操作代码改异步操作,客户端软件界面错误如下:一点击数据源配置模块,就提示数据解析错误,请重启客户端。除了首页模块是正确的以外,点击文件修复和授权信息界面信息都出不来,而且软件卡死,按右上角的关闭键也无法退出。项目采用.net三层架构,修改后的socket类的异步传输部代码如下: ![![图片说明](https://img-ask.csdn.net/upload/201509/17/1442497613_763975.png)图片说明](https://img-ask.csdn.net/upload/201509/17/1442497607_172400.png) ![![![![![![![![![![![图片说明](https://img-ask.csdn.net/upload/201509/17/1442498556_560286.png)图片说明](https://img-ask.csdn.net/upload/201509/17/1442498594_534760.png)图片说明](https://img-ask.csdn.net/upload/201509/17/1442498557_279873.png)图片说明](https://img-ask.csdn.net/upload/201509/17/1442498469_791285.png)图片说明](https://img-ask.csdn.net/upload/201509/17/1442498420_801626.png)图片说明](https://img-ask.csdn.net/upload/201509/17/1442498378_653933.png)图片说明](https://img-ask.csdn.net/upload/201509/17/1442498306_209580.png)图片说明](https://img-ask.csdn.net/upload/201509/17/1442498276_400425.png)图片说明](https://img-ask.csdn.net/upload/201509/17/1442498211_949856.png)图片说明](https://img-ask.csdn.net/upload/201509/17/1442498103_147396.png)图片说明](https://img-ask.csdn.net/upload/201509/17/1442498033_216971.png)

C#里用socket收发udp数据的问题

一:用udp收发数据,为什么接收方要发一帧数之后才能接收到数据? private Socket SetupUdpSocketObject(string localIp, string localPort, string remoteIp, string remotePort) { //得到本机IP,设置TCP端口号 var ip = new IPEndPoint(IPAddress.Parse(localIp), int.Parse(localPort)); var ret = new Socket(AddressFamily.InterNetwork, SocketType.Dgram, ProtocolType.Udp); //绑定网络地址 ret.Bind(ip); var sender = new IPEndPoint(IPAddress.Any, 0); _remote = sender; EndPoint point = new IPEndPoint(IPAddress.Parse(remoteIp), int.Parse(remotePort)); ret.SendTo(new byte[] { 1, 2, 3 }, point); //发送一帧数据才能收到数据 return ret; } private void ProcessUdpData() { while (true) { var data = new byte[DataMaximumLength]; //发送接受信息 var recv = _udpSocket.ReceiveFrom(data, ref _remote); _recorder.RecordBytes(data, 0, recv); //记录数据 var cell = new AzimuthCell(data); NotifyAllObservers(cell); //发送通知 } } 如果不写ret.SendTo(new byte[] { 1, 2, 3 }, point); 就收不到数据。 二:socket接收和发送数据我都是用线程发送,一个while(true)循环,反复sendto发缓存区,反复recvfrom,但是这样两个线程的占用率很高,有没有其他办法收发数据,除了beginsendto和beginrecvfrom

C# 异步下载问题

public string IPAdress = "xx.xx.xx.xx"; public string ftpUser = "xxx"; public string ftpPassWord = "xxxxxxxx"; public string LocalAdress = "D://"; public string FileName = "xx.txt"; private void Upload() { Uri uri = new Uri("ftp://" + IPAdress + "/" + FileName); //定义FtpWebRequest,并设置相关属性 FtpWebRequest uploadRequest = (FtpWebRequest)WebRequest.Create(uri); uploadRequest.Method = WebRequestMethods.Ftp.UploadFile; uploadRequest.Credentials = new NetworkCredential(ftpUser, ftpPassWord); //开始以异步方式打开请求的内容流以便写入 uploadRequest.BeginGetRequestStream(new AsyncCallback(EndGetStreamCallback), uploadRequest); } private void EndGetStreamCallback(IAsyncResult ar) { //用户定义对象,其中包含该操作的相关信息,在这里得到FtpWebRequest FtpWebRequest uploadRequest = (FtpWebRequest)ar.AsyncState; //结束由BeginGetRequestStream启动的挂起的异步操作 //必须调用EndGetRequestStream方法来完成异步操作 //通常EndGetRequestStream由callback所引用的方法调用 Stream requestStream = uploadRequest.EndGetRequestStream(ar); FileStream fileStream = File.Open(@""+LocalAdress + FileName, FileMode.Open); byte[] buffer = new byte[2048]; int bytesRead; float size; while (true) { bytesRead = fileStream.Read(buffer, 0, buffer.Length); startbye += bytesRead; if (bytesRead == 0) break; Debug.Log(startbye); size = fileStream.Length; //本地的文件流数据写到请求流 requestStream.Write(buffer, 0, bytesRead); } requestStream.Close(); fileStream.Close(); //开始以异步方式向FTP服务器发送请求并从FTP服务器接收响应 uploadRequest.BeginGetResponse(new AsyncCallback(EndGetResponseCallback), uploadRequest); } private void EndGetResponseCallback(IAsyncResult ar) { FtpWebRequest uploadRequest = (FtpWebRequest)ar.AsyncState; //结束由BeginGetResponse启动的挂起的异步操作 FtpWebResponse uploadResponse = (FtpWebResponse)uploadRequest.EndGetResponse(ar); Debug.Log(uploadResponse.StatusDescription); Debug.Log("Upload complete"); } 求教大神!!!!!如何把这段异步上传修改成异步下载!!!

C# socket networkstream 接收数据

最近在做c/s,客户端用C#的Socket进行通信。接收数据开单独的接收线程使用networkstream进行接收 接收的方法大体上跟网上流传的一样 do { int readSize = mNetworkstream.Read(bytes, 0, 1024); if (readSize > 0) { //do sth } }while(mNetworkstream.DataAvailable) 这样接收局内网或者单机没问题,但是放到外网测试网络不稳定就接收不全。 搜集很多资料,也试过在发送Socket包之前加个包大小,然后在while中增加判断是否读到包的大小,可是一样接不全,中间好像掺杂了一些没用的数据? 我一个包很容易超过byte[10240],而且要整个包接收完才能处理数据。 请问C# Socket使用networkstream怎样才能接收完全呢? ps:也有听说过异步networkstream.beginread接收。鉴于网上一大抄,各种人贴各种代码片段根本就没用。有些有用但只能接收一次。。。 如果有beginread相关代码也希望大牛们贴出来参考一下,不要贴代码片段。。。 谢谢了~

C# 关于Socket忽略证书的443端口连接问题

this.sslStream = new SslStream(this._client.GetStream(), false, new RemoteCertificateValidationCallback(this.CheckValidationResult), null); try { this.sslStream.AuthenticateAsClient(serverip, null, SslProtocols.Tls, false); } ......... 最近在做一个socket的项目,服务器是外部的(无法下载证书),上面的代码是反编译以前的客户端程序,异步socket在证书部分直接传的null,但是测试始终显示握手失败。请问下大家有这么方面的经验么?是因为我用的同步socket引起的问题吗?

c# Socket,tcp接收时会粘包?

private void RecMsg(object sokConnectionparn) { Socket sokClient = sokConnectionparn as Socket; while (true) { byte[] arrMsgRec = new byte[1024 * 1024 * 3+3]; // 将接受到的数据存入到输入 arrMsgRec中; int length = -1; try { length = sokClient.Receive(arrMsgRec); // 接收数据,并返回数据的长度; } catch (SocketException se) { ShowMsg("异常:" + se.Message); dictSocket.Remove(sokClient.RemoteEndPoint.ToString()); dictThread.Remove(sokClient.RemoteEndPoint.ToString()); DeleteLib(sokClient.RemoteEndPoint.ToString()); break; } catch (Exception e) { ShowMsg("异常:" + e.Message); dictSocket.Remove(sokClient.RemoteEndPoint.ToString()); dictThread.Remove(sokClient.RemoteEndPoint.ToString()); DeleteLib(sokClient.RemoteEndPoint.ToString()); break; } try { if (arrMsgRec[0] == 0) // 表示接收到的是数据; { string strMsg = System.Text.Encoding.UTF8.GetString(arrMsgRec, 1, length - 1);// 将接受到的字节数据转化成字符串; ShowMsg(strMsg); } if (arrMsgRec[0] == 1) // 表示接收到的是文件; { filesource = sokClient.RemoteEndPoint.ToString(); //var i = BitConverter.ToInt32(arrMsgRec, arrMsgRec.Length-3); if (System.Text.Encoding.UTF8.GetString(arrMsgRec, 1, length - 1).Contains("FileName")) { string strMsg = System.Text.Encoding.UTF8.GetString(arrMsgRec, 1, length - 1); bpp.FileName = strMsg.Split(':')[1]; bpp.Index = 0; savepath = ""; savepath = Path.Combine(savepath, bpp.FileName); } else if (System.Text.Encoding.UTF8.GetString(arrMsgRec, 1, length - 1).Contains("PackageCount")) { string strMsg = System.Text.Encoding.UTF8.GetString(arrMsgRec, 1, length - 1); bpp.PackageCount = int.Parse(strMsg.Split(':')[1]); } else if (arrMsgRec[1] == 22 && arrMsgRec[2] == 33) { //int i = BitConverter.ToInt32(arrMsgRec, arrMsgRec.Length - 3); byte[] buffer = new byte[length - 3]; Buffer.BlockCopy(arrMsgRec, 3, buffer, 0, buffer.Length); if (!string.IsNullOrEmpty(bpp.FileName)) { Thread fw = new Thread(() => FileWrite(savepath, bpp.Index, 1024 * 1024 * 3, buffer.Length, buffer)); fw.IsBackground = true; fw.Start(); } } else { stringtobyte("Err:" + bpp.Index.ToString(), 1); dictSocket[filesource].Send(stringtobyte("Err:" + bpp.Index.ToString(), 1)); } } } catch(Exception ex) { //MessageBox.Show(ex.Message); } } } 用这个作为后台线程接收,然后发文件(客户端线程分包自动发的)的同时传输信息的话会粘包吧,好像是这个说法,就是那一包文件数据会收不到,然后聊天信息会出现乱码,求教怎么解决,新手实在搞不定- -谢谢.

C# socket通讯的一个问题请教一下大家

![图片说明](https://img-ask.csdn.net/upload/201608/30/1472554027_499837.png) ![图片说明](https://img-ask.csdn.net/upload/201608/30/1472554037_889371.png) 如图 连接服务器完成后第二次Send发送数据会报错::: 你的主机中的软件中止了一个已建立的连接。 不知道是什么原因导致的,主要是对通讯这方面也不熟悉。大神帮我分析一下,不胜感激

c# socket如何实现上一条指令发送并收到返回成功后再发送下一条指令呢?

现在在做一个通过socket给下位机发送硬件控制指令的项目,以前使用串口,流程好控制,都是同步的:发送-->等待N毫秒-->接收数据-->处理数据,现在要改成网口,可是socket的发送和接收不在一个方法中,导致我没法实现上一条指令接收完成后(result=true)才允许发送下一条指令,哪位大牛给点思路呢?Thanks

Socket异步传输远程主机强迫关闭了一个现有的链接

class AsyncProgram { static Thread thead = null; static Thread theadclient = null; static int port = 12345; static Socket server = null; static Socket client = null; static int buffersize = 40960000; static void Main() { thead = new Thread(new ThreadStart(() => { IPEndPoint netPoint = new IPEndPoint(IPAddress.Any,port); server = new Socket(AddressFamily.InterNetwork,SocketType.Stream,ProtocolType.Tcp); server.Bind(netPoint); server.Listen(10); theadclient.Start(); while (true) { server.BeginAccept(new AsyncCallback(AcceptCallBack),server); } })); thead.Start(); theadclient = new Thread(new ThreadStart(() => { IPEndPoint netpoint = new IPEndPoint(IPAddress.Parse("127.0.0.1"),port); client = new Socket(AddressFamily.InterNetwork,SocketType.Stream,ProtocolType.Tcp); client.BeginConnect(netpoint, new AsyncCallback(ConnectCallBack), client); })); } static void AcceptCallBack(IAsyncResult ar) { Socket serve = ar.AsyncState as Socket; serve.EndAccept(ar); } static void sendSata(Socket client) { byte[] buffers = new byte[buffersize]; FileStream file = new FileStream(@"E:\temp\iTunes64Setup.exe", FileMode.Open); int readCount = file.Read(buffers, 0, buffersize); client.BeginSend(buffers, 0, readCount, 0, new AsyncCallback(SendCallBack), client); while (readCount > 0) { client.BeginSend(buffers, 0, readCount, 0, new AsyncCallback(SendCallBack), client); } file.Close(); client.Disconnect(false); client.Close(); } static void ConnectCallBack(IAsyncResult ar) { Socket client = ar.AsyncState as Socket; client.EndConnect(ar); sendSata(client); } static void SendCallBack(IAsyncResult ar) { Socket client = ar.AsyncState as Socket; client.EndSend(ar); } }

c#socket实验点对点通信的程序时通信不成功报错

刚学习用c#的socket来通信,在同一个局域网的两台电脑进行测试,出现不能链接的情况,如图所示,请问是什么原因 界面如下:![图片说明](https://img-ask.csdn.net/upload/201601/13/1452685461_283906.png) 报错如下:![图片说明](https://img-ask.csdn.net/upload/201601/13/1452685489_77017.png) 代码如下 ``` using System; using System.Collections.Generic; using System.ComponentModel; using System.Data; using System.Drawing; using System.Linq; using System.Text; using System.Windows.Forms; using System.Net; using System.Net.Sockets; using System.Threading; using System.IO; namespace _508P2PServer { public partial class Form1 : Form { Thread td; TcpListener tcpl; static string message = ""; public Form1() { InitializeComponent(); } void StartListen() { tcpl = new TcpListener(888); tcpl.Start(); while(true) { TcpClient tclient = tcpl.AcceptTcpClient(); NetworkStream netstream = tclient.GetStream(); byte[] mbyte = new byte[1024]; int i = netstream.Read(mbyte,0,mbyte.Length); message = Encoding.Default.GetString(mbyte,0,i); } } private void Form1_Load(object sender, EventArgs e) { td = new Thread(new ThreadStart(this.StartListen)); td.Start(); timer1.Start(); } private void button2_Click(object sender, EventArgs e) { try { IPAddress[] ip = Dns.GetHostAddresses(Dns.GetHostName()); string strmes = this.textBox2.Text + ip[0].ToString() + DateTime.Now.ToLongTimeString() + "\n" + richTextBox2.Text + "\n"; TcpClient client = new TcpClient(textBox1.Text, 888); NetworkStream netstream = client.GetStream(); StreamWriter streamw = new StreamWriter(netstream, Encoding.Default); streamw.Write(strmes); streamw.Flush(); streamw.Close(); client.Close(); richTextBox1.AppendText(strmes); richTextBox1.ScrollToCaret(); richTextBox2.Clear(); } catch (Exception ex) { MessageBox.Show(ex.Message); } } private void timer1_Tick(object sender, EventArgs e) { if (message != "") { richTextBox1.AppendText(message); richTextBox1.ScrollToCaret(); message = ""; } } private void Form1_FormClosed(object sender, FormClosedEventArgs e) { if (this.tcpl != null) { tcpl.Stop(); } if (td != null) { if(td.ThreadState==ThreadState.Running) { td.Abort(); } } } } } ``` 请问问题出在哪

socket如何实现其中的发送回调函数和完成发送的代码功能

c#socket异步通信中的SendCallback类包含在静态类中如何实现其中的发送回调函数和完成发送的代码功能 以及错误如何解决![![图片说明](https://img-ask.csdn.net/upload/201509/16/1442378500_213820.jpg)图片说明](https://img-ask.csdn.net/upload/201509/16/1442378441_762401.jpg) using Newtonsoft.Json; using System; using System.Collections.Generic; using System.IO; using System.Linq; using System.Net; using System.Net.Sockets; using System.Text; using System.Threading.Tasks; using System.ComponentModel; using System.Data; using System.Windows.Forms; using System.Threading; namespace DAL { /// <summary> /// Socket接口 /// </summary> static class socket { //Socket public static Socket clientSocket; /// <summary> /// socket连接 /// </summary> /// <returns> /// true 成功 /// false 失败 /// </returns> public static bool SocketConnect() { byte[] receive_buff = new byte[256]; ManualResetEvent connectDone = new ManualResetEvent(false); //连接的信号 ManualResetEvent readDone = new ManualResetEvent(false); //读信号 ManualResetEvent sendDone = new ManualResetEvent(false); //发送结束 //从配置文件获取IP string SocketIP = DAL.Common.ReadConfigString("Recover", "IP"); //从配置文件获取端口 int SocketPort = Convert.ToInt32(DAL.Common.ReadConfigString("Recover", "Port")); //创建IP地址 IPAddress IP = IPAddress.Parse(SocketIP); try { //创建socket实例 clientSocket = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp); //创建网络端点 IPEndPoint ipEnd = new IPEndPoint(IP, SocketPort); //EndPoint ipEnd = (EndPoint)remotepoint; //与目标终端连接 clientSocket.BeginConnect(ipEnd, new AsyncCallback(ConnectCallback), clientSocket);//调用回调函数 connectDone.WaitOne(); if (clientSocket.Connected) { return true; } else { return false; } } catch (Exception e) { string strError = ""; strError += "\r\n SocketIP = " + SocketIP.ToString(); strError += "\r\n SocketPort = " + SocketPort.ToString(); DAL.Common.WriteErrorLog(e, strError); return false; } } public static void ConnectCallback(IAsyncResult ar) { bool connect_flag = false; ManualResetEvent connectDone = new ManualResetEvent(false); //连接的信号 Socket client = (Socket)ar.AsyncState; client.EndConnect(ar); connect_flag = true; connectDone.Set(); } /// <summary> /// Socket发送数据 /// </summary> /// <param name="strSend"> /// 数据的内容 /// </param> public static void SocketSend(string strSend) { Socket tcpsend; //发送创建套接字 ManualResetEvent sendDone = new ManualResetEvent(false);//发送结束 int length = strSend.Length; Byte[] Bysend = new byte[length]; try { Bysend = System.Text.Encoding.Default.GetBytes(strSend); //将字符串指定到指定Byte数组 tcpsend.BeginSend(Bysend, 0, Bysend.Length, 0, new AsyncCallback(SendCallback), tcpsend); //异步发送数据 sendDone.WaitOne(); } catch (Exception e) { string strError = ""; DAL.Common.WriteErrorLog(e, strError); } } private void SendCallback(IAsyncResult ar) //发送的回调函数 { Socket client = (Socket)ar.AsyncState; int bytesSend = client.EndSend(ar); //完成发送 sendDone.Set(); }![图片说明](https://img-ask.csdn.net/upload/201509/16/1442378304_186857.jpg)

c#异步通信代码错误问题

public void ConnectCallback(IAsyncResult ar) { Socket client = (Socket)ar.AsyncState; client.EndConnect(ar); bool connect_flag = false; connect_flag = true; ManualResetEvent connectDone = new ManualResetEvent(false); //连接的信号 connectDone.Set(); } //vs的这段代码中 ,bool connect_flag的connect_flag报了一个警告错误,变量connect_flag已赋值,但是其值从未使用过。如何修改? public static MODEL.DataSourceVersionQuery BrowseDataSource_QueryVersionData() { MODEL.DataSourceVersionQuery result = new MODEL.DataSourceVersionQuery(); //获取数据包 string strPacket = BrowseDataSource_PrepareVersionPacket(); //向服务端提交查询版本信息 string str = DAL.socket.GetSocketData(strPacket); //DAL.socket.GetSocketData(strPacket) vs报了一个错误,非静态字段、方法或属性DAL.socket.GetSocketData(string)“要求对象引用。如何修改? 还有这个错误![图片说明](https://img-ask.csdn.net/upload/201509/16/1442412249_893824.png) 另外我想把DAL中的socket.cs的 public byte[] bytesReceived { get; set; }这段移动到Model中而不报错要如何修改? DAL中socket完整代码如下: using Newtonsoft.Json; using System; using System.Collections.Generic; using System.IO; using System.Linq; using System.Net; using System.Net.Sockets; using System.Text; using System.Threading.Tasks; using System.ComponentModel; using System.Data; using System.Windows.Forms; using System.Threading; namespace DAL { /// <summary> /// Socket接口 /// </summary> class socket { //Socket public Socket clientSocket; /// <summary> /// socket连接 /// </summary> /// <returns> /// true 成功 /// false 失败 /// </returns> public bool SocketConnect() { byte[] bytesReceived = new byte[256]; ManualResetEvent connectDone = new ManualResetEvent(false); //连接的信号 ManualResetEvent sendDone = new ManualResetEvent(false); //发送结束 //从配置文件获取IP string SocketIP = DAL.Common.ReadConfigString("Recover", "IP"); //从配置文件获取端口 int SocketPort = Convert.ToInt32(DAL.Common.ReadConfigString("Recover", "Port")); //创建IP地址 IPAddress IP = IPAddress.Parse(SocketIP); try { //创建socket实例 clientSocket = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp); //创建网络端点 IPEndPoint ipEnd = new IPEndPoint(IP, SocketPort); //与目标终端连接 clientSocket.BeginConnect(ipEnd, new AsyncCallback(ConnectCallback), clientSocket);//调用回调函数 connectDone.WaitOne(); if (clientSocket.Connected) { return true; } else { return false; } } catch (Exception e) { string strError = ""; strError += "\r\n SocketIP = " + SocketIP.ToString(); strError += "\r\n SocketPort = " + SocketPort.ToString(); DAL.Common.WriteErrorLog(e, strError); return false; } } /// <summary> /// 异步连接的回调函数 /// </summary> /// <param name="ar"></param> public void ConnectCallback(IAsyncResult ar) { Socket client = (Socket)ar.AsyncState; client.EndConnect(ar); bool connect_flag = false; connect_flag = true; ManualResetEvent connectDone = new ManualResetEvent(false); //连接的信号 connectDone.Set(); } /// <summary> /// Socket发送数据 /// </summary> /// <param name="strSend"> /// 数据的内容 /// </param> public void SocketSend(string strSend) { Socket clientSocket; //发送创建套接字 int length = strSend.Length; Byte[] bytesSent = new byte[length]; clientSocket = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp); try { bytesSent = System.Text.Encoding.Default.GetBytes(strSend); //将字符串指定到指定Byte数组 clientSocket.BeginSend(bytesSent, 0, bytesSent.Length, 0, new AsyncCallback(SendCallback), clientSocket); //异步发送数据 ManualResetEvent sendDone = new ManualResetEvent(false);//发送结束 sendDone.WaitOne(); } catch (Exception e) { string strError = ""; DAL.Common.WriteErrorLog(e, strError); } } public void SendCallback(IAsyncResult ar) //发送的回调函数 { ManualResetEvent sendDone = new ManualResetEvent(false); //发送结束 Socket client = (Socket)ar.AsyncState; int bytesSend = client.EndSend(ar); //完成发送 sendDone.Set(); } /// <summary> /// Socket接收数据 /// </summary> /// <returns> /// 收到的数据 /// </returns> public string SocketReceive() { string result = ""; try { MemoryStream stream = new MemoryStream(); Byte[] bytesReceived = new Byte[256]; clientSocket.BeginReceive(bytesReceived, 0, bytesReceived.Length, 0, new AsyncCallback(ReceiveCallback), clientSocket); ManualResetEvent sendDone = new ManualResetEvent(false); //发送结束 sendDone.WaitOne(); } catch (Exception e) { string strError = ""; DAL.Common.WriteErrorLog(e, strError); } return result; } public void ReceiveCallback(IAsyncResult ar) { Socket client = (Socket)ar.AsyncState; //获取句柄 int bytesread = client.EndReceive(ar); if (bytesread > 0) { clientSocket.BeginReceive(bytesReceived, 0, bytesReceived.Length, 0, new AsyncCallback(ReceiveCallback), client); string content = Encoding.ASCII.GetString(bytesReceived, 0, bytesReceived.Length); } else { ManualResetEvent readDone = new ManualResetEvent(false); //读信号 readDone.Set(); } } /// <summary> /// Socket通信 /// </summary> /// <param name="strSend"> /// 发送的信息 /// </param> /// <returns> /// 包体的内容 /// </returns> public string GetSocketData(string strSend) { string strDatas = ""; string strResult = ""; string strExtLength = ""; try { //Socket连接 SocketConnect(); //发送信息 SocketSend(strSend); //接收服务器的信息 strResult = SocketReceive(); //获取扩展信息的长度 strExtLength = strResult.Substring(16, 12); int ExtLength = Convert.ToInt32(strExtLength); //扩展信息,暂不使用 //string strExtInfo = strResult.Substring(32, ExtLength); //获取包体的内容 strDatas = strResult.Substring(ExtLength + 32); //strDatas = decodedString; } catch (Exception e) { string strError = ""; strError += "\r\n strResult = " + strResult; strError += "\r\n strExtLength = " + strExtLength; DAL.Common.WriteErrorLog(e, strError); strDatas = ""; } return strDatas; } public string SocketReceiveFile(string FileName) { string result = ""; try { MemoryStream streamPacketLength = new MemoryStream(); Byte[] bytesPacketLength = new Byte[16]; clientSocket.Receive(bytesPacketLength, bytesPacketLength.Length, 0); streamPacketLength.Write(bytesPacketLength, 0, bytesPacketLength.Length); result = System.Text.Encoding.Default.GetString(streamPacketLength.ToArray()); int PacketLength = Convert.ToInt32(result); streamPacketLength.Close(); MemoryStream streamExtLength = new MemoryStream(); Byte[] bytesExtLength = new Byte[12]; clientSocket.Receive(bytesExtLength, bytesExtLength.Length, 0); streamExtLength.Write(bytesExtLength, 0, bytesExtLength.Length); result = System.Text.Encoding.Default.GetString(streamExtLength.ToArray()); int ExtLength = Convert.ToInt32(result); streamExtLength.Close(); MemoryStream streamProtocol = new MemoryStream(); Byte[] bytesProtocol = new Byte[4]; clientSocket.Receive(bytesProtocol, bytesProtocol.Length, 0); streamProtocol.Write(bytesProtocol, 0, bytesProtocol.Length); result = System.Text.Encoding.Default.GetString(streamProtocol.ToArray()); string Protocol = result; streamProtocol.Close(); MemoryStream streamExtInfo = new MemoryStream(); Byte[] bytesExtInfo = new Byte[ExtLength]; clientSocket.Receive(bytesExtInfo, bytesExtInfo.Length, 0); streamExtInfo.Write(bytesExtInfo, 0, bytesExtInfo.Length); result = System.Text.Encoding.Default.GetString(streamExtInfo.ToArray()); byte[] Buffer = Convert.FromBase64String(result); string strExtInfo = UTF8Encoding.UTF8.GetString(Buffer); streamExtInfo.Close(); MODEL.FileTrackQuery ExtInfo = new MODEL.FileTrackQuery(); ExtInfo = JsonConvert.DeserializeObject<MODEL.FileTrackQuery>(strExtInfo); if (ExtInfo.code == "00") { FileInfo fi = new FileInfo(FileName); DirectoryInfo di = fi.Directory; if (!di.Exists) { di.Create(); } FileStream streamPacketInfo = new FileStream(FileName, FileMode.Create); if (PacketLength > 0) { Byte[] bytesPacketInfo = new Byte[PacketLength]; int bytes = 0; do { bytes = clientSocket.Receive(bytesPacketInfo, bytesPacketInfo.Length, 0); streamPacketInfo.Write(bytesPacketInfo, 0, bytes); } while (bytes > 0); } streamPacketInfo.Close(); } clientSocket.Close(); string strLogFile = System.AppDomain.CurrentDomain.BaseDirectory + "debug.txt"; StreamWriter sw = new StreamWriter(strLogFile, true); sw.WriteLine("PacketLength : " + PacketLength.ToString()); sw.WriteLine("ExtLength : " + ExtLength.ToString()); sw.WriteLine("strExtInfo : " + strExtInfo); sw.WriteLine("ExtInfo.code : " + ExtInfo.code); sw.WriteLine("\n------------------------------------------------------------------------\n"); sw.Flush(); sw.Close(); } catch (Exception e) { string strError = ""; DAL.Common.WriteErrorLog(e, strError); } return result; } public string GetSocketFile(string strSend, string FileName) { string strDatas = ""; string strResult = ""; string strExtLength = ""; try { //Socket连接 SocketConnect(); //发送信息 SocketSend(strSend); //接收服务器的信息 strResult = SocketReceiveFile(FileName); //获取扩展信息的长度 //strExtLength = strResult.Substring(16, 12); //int ExtLength = Convert.ToInt32(strExtLength); //扩展信息,暂不使用 //string strExtInfo = strResult.Substring(32, ExtLength); //获取包体的内容 //strDatas = strResult.Substring(ExtLength + 32); } catch (Exception e) { string strError = ""; strError += "\r\n strResult = " + strResult; strError += "\r\n strExtLength = " + strExtLength; DAL.Common.WriteErrorLog(e, strError); strDatas = ""; } return strDatas; } public byte[] bytesReceived { get; set; } } } MODEL完整代码如下: using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; namespace MODEL { public enum ClientEditionEnum { Enterprise,//企业版 Personal,//个人版 Internal,//内部版 None,//error } /// <summary> /// 授权文件内容 /// </summary> public class AuthorizeFileInfo { public string startTime { get; set; } public string expiryTime { get; set; } public string licenseID { get; set; } public string licensePassword { get; set; } public string terminalID { get; set; } public string customName { get; set; } public string customID { get; set; } public AuthorizeFileInfo() { startTime = ""; expiryTime = ""; licenseID = ""; licensePassword = ""; terminalID = ""; customName = ""; customID = ""; } } /// <summary> /// 通用返回值 /// </summary> /// public class CommonResult { public string code { get; set; } public string message { get; set; } public CommonResult() { code = ""; message = ""; } } public class EnterpriseConfirmAuthorizeDatas { public string sessionID { get; set; } public EnterpriseConfirmAuthorizeDatas() { sessionID = ""; } } /// <summary> /// 企业版授权校验接口 /// </summary> public class EnterpriseConfirmAuthorizeResult { public string code { get; set; } public string message { get; set; } public EnterpriseConfirmAuthorizeDatas datas { get; set; } public EnterpriseConfirmAuthorizeResult() { code = ""; message = ""; datas = new EnterpriseConfirmAuthorizeDatas(); } } public class PersonalConfirmAuthorizeDatas { public string sessionID { get; set; } public string licenseInfo { get; set; } public PersonalConfirmAuthorizeDatas() { sessionID = ""; licenseInfo = ""; } } /// <summary> /// 个人版授权校验接口 /// </summary> public class PersonalConfirmAuthorizeResult { public string code { get; set; } public string message { get; set; } public PersonalConfirmAuthorizeDatas datas { get; set; } public PersonalConfirmAuthorizeResult() { code = ""; message = ""; datas = new PersonalConfirmAuthorizeDatas(); } } /// <summary> /// 鉴权信息,每次调用安全接口时使用 /// </summary> public class LicInfo { public string licenseID { get; set; } public string licensePassword { get; set; } public string terminalID { get; set; } public string deviceID { get; set; } public string sessionID { get; set; } public LicInfo() { licenseID = ""; licensePassword = ""; terminalID = ""; deviceID = ""; sessionID = ""; } } /// <summary> /// java引擎的参数 /// </summary> public class JavaEngineArg { public string licenseID { get; set; } public string licensePassword { get; set; } public string terminalID { get; set; } public string customName { get; set; } public string customID { get; set; } public string deviceID { get; set; } public JavaEngineArg() { licenseID = ""; licensePassword = ""; terminalID = ""; customName = ""; customID = ""; deviceID = ""; } } /// <summary> /// 用户登录接口(一),非安全接口 /// </summary> /// public class UserInfoUnSafe { public string userID { get; set; } public string userName { get; set; } public string departmentName { get; set; } public UserInfoUnSafe() { userID = ""; userName = ""; departmentName = ""; } } public class UserLoginUnSafe { public string code { get; set; } public string message { get; set; } public UserInfoUnSafe datas { get; set; } public UserLoginUnSafe() { code = ""; message = ""; datas = new UserInfoUnSafe(); } } /// <summary> /// 个人版用户登录接口,非安全接口 /// </summary> /// public class UserInfoForPersonal { public string userID { get; set; } public string userName { get; set; } public string departmentName { get; set; } public string licenseInfo { get; set; } public UserInfoForPersonal() { userID = ""; userName = ""; departmentName = ""; licenseInfo = ""; } } public class UserLoginForPersonal { public string code { get; set; } public string message { get; set; } public UserInfoForPersonal datas { get; set; } public UserLoginForPersonal() { code = ""; message = ""; datas = new UserInfoForPersonal(); } } /// <summary> /// 用户登录接口(二),安全接口 /// </summary> /// public class UserInfoSafe { public string userSessionID { get; set; } public string userID { get; set; } public string userName { get; set; } public string departmentName { get; set; } public string activeTime { get; set; } public UserInfoSafe() { userSessionID = ""; userID = ""; userName = ""; departmentName = ""; activeTime = ""; } } public class UserLoginSafe { public string code { get; set; } public string message { get; set; } public UserInfoSafe datas { get; set; } public UserLoginSafe() { code = ""; message = ""; datas = new UserInfoSafe(); } } /// <summary> /// 更新检查接口 /// </summary> /// public class SingleVersion { public string softID { get; set; } public int version { get; set; } public SingleVersion() { softID = ""; version = new int(); } } public class Versions { public List<SingleVersion> versions { get; set; } public Versions() { versions = new List<SingleVersion>(); } } public class VersionUpdate { public string softID { get; set; } public int version { get; set; } public string url { get; set; } public VersionUpdate() { softID = ""; version = new int(); url = ""; } } public class VersionCheck { public string code { get; set; } public string message { get; set; } public List<VersionUpdate> datas { get; set; } public VersionCheck() { code = ""; message = ""; datas = new List<VersionUpdate>(); } } /// <summary> /// 数据源信息查询接口 /// </summary> /// public class OptInfoQuery { public string createUserID { get; set; } public string createUserName { get; set; } public string createUserTime { get; set; } public OptInfoQuery() { createUserID = ""; createUserName = ""; createUserTime = ""; } } public class Period { public int cycle { get; set; } public int cycleUnit { get; set; } public string timer { get; set; } public Period() { cycle = 1; cycleUnit = 1; timer = DateTime.Now.ToString("yyyy/MM/dd HH:mm:ss"); } } public class StrategyConfig { public int backType { get; set; } public int taskType { get; set; } public Period config { get; set; } public StrategyConfig() { backType = 0; taskType = 1; config = new Period(); } } public class FilterFileSuffix { public string suffix { get; set; } public FilterFileSuffix() { suffix = ""; } } public class Scan { public int scanType { get; set; } public string root { get; set; } public bool scanHideFile { get; set; } public string verifyCompleteName { get; set; } public int verifyCompleteMaxCount { get; set; } public int verifyCompleteTimer { get; set; } public string fileAttrGainer { get; set; } public bool recordCanNotReadFileInfo { get; set; } public bool recordEmptyDirectory { get; set; } public bool recordEmptyFile { get; set; } public List<FilterFileSuffix> filterFileSuffix { get; set; } public Scan() { scanType = 2; root = ""; scanHideFile = false; verifyCompleteName = ""; verifyCompleteMaxCount = 5; verifyCompleteTimer = 10000; fileAttrGainer = "null"; recordCanNotReadFileInfo = false; recordEmptyDirectory = false; recordEmptyFile = false; filterFileSuffix = new List<FilterFileSuffix>(); } } public class DataSourceConfigQuery { public int status { get; set; } public int dataSourceType { get; set; } public string dataSourceID { get; set; } public string dataSourceName { get; set; } public string dataSourceDescription { get; set; } public Scan config { get; set; } public DataSourceConfigQuery() { status = 0; dataSourceType = 0; dataSourceID = ""; dataSourceName = ""; dataSourceDescription = ""; config = new Scan(); } } public class DatasQuery { public OptInfoQuery optInfo { get; set; } public StrategyConfig strategyConfig { get; set; } public DataSourceConfigQuery dataSourceConfig { get; set; } public DatasQuery() { optInfo = new OptInfoQuery(); strategyConfig = new StrategyConfig(); dataSourceConfig = new DataSourceConfigQuery(); } } public class DataSourceInfoQuery { public string code { get; set; } public string message { get; set; } public List<DatasQuery> datas { get; set; } public DataSourceInfoQuery() { code = ""; message = ""; datas = new List<DatasQuery>(); } } public class WebSite { public string ExpirationTime { get; set; } public string WebSiteSpace { get; set; } public bool DataBaseEnable { get; set; } public string DataBaseUserName { get; set; } public string DataBasePassword { get; set; } public string DataBaseMark { get; set; } public string WebSiteAdmin { get; set; } public string WebSitePassword { get; set; } public WebSite() { ExpirationTime = ""; WebSiteSpace = ""; DataBaseEnable = false; DataBaseUserName = ""; DataBasePassword = ""; DataBaseMark = ""; WebSiteAdmin = ""; WebSitePassword = ""; } } public class WebSiteDatasQuery { public OptInfoQuery optInfo { get; set; } public StrategyConfig strategyConfig { get; set; } public DataSourceConfigQuery dataSourceConfig { get; set; } public WebSite webSiteConfig { get; set; } public WebSiteDatasQuery() { optInfo = new OptInfoQuery(); strategyConfig = new StrategyConfig(); dataSourceConfig = new DataSourceConfigQuery(); webSiteConfig = new WebSite(); } } public class WebSiteDataSourceInfoQuery { public string code { get; set; } public string message { get; set; } public List<WebSiteDatasQuery> datas { get; set; } public WebSiteDataSourceInfoQuery() { code = ""; message = ""; datas = new List<WebSiteDatasQuery>(); } } /// <summary> /// 新增数据源接口 /// </summary> /// public class OptInfoNew { public bool forceFlag { get; set; } public OptInfoNew() { forceFlag = true; } } public class DataSourceConfigNew { public int dataSourceType { get; set; } public string dataSourceName { get; set; } public string dataSourceDescription { get; set; } public Scan config { get; set; } public DataSourceConfigNew() { dataSourceType = 0; dataSourceName = ""; dataSourceDescription = ""; config = new Scan(); } } public class DataSourceNew { public OptInfoNew optInfo { get; set; } public StrategyConfig strategyConfig { get; set; } public DataSourceConfigNew dataSourceConfig { get; set; } public DataSourceNew() { optInfo = new OptInfoNew(); strategyConfig = new StrategyConfig(); dataSourceConfig = new DataSourceConfigNew(); } } /// <summary> /// 修改数据源接口 /// </summary> /// public class DataSourceModify { public StrategyConfig strategyConfig { get; set; } public DataSourceConfigQuery dataSourceConfig { get; set; } public DataSourceModify() { strategyConfig = new StrategyConfig(); dataSourceConfig = new DataSourceConfigQuery(); } } /// <summary> /// 停用/启用数据源接口 /// </summary> /// public class DataSourceStatus { public string dataSourceID { get; set; } public int optType { get; set; } public DataSourceStatus() { dataSourceID = ""; optType = new int(); } } /// <summary> /// 数据源数据,仅用于存放数据 /// </summary> /// public class DataSourceData { public List<DatasQuery> datas { get; set; } public DataSourceData() { datas = new List<DatasQuery>(); } } /// <summary> /// WebSite数据源数据,仅用于存放数据 /// </summary> /// public class WebSiteDataSourceData { public List<WebSiteDatasQuery> datas { get; set; } public WebSiteDataSourceData() { datas = new List<WebSiteDatasQuery>(); } } /// <summary> /// 文件恢复,版本查询 /// </summary> /// public class DataSourceVersionArg { // 通讯令牌 public string secretKey { get; set; }//由token进过MD5->BASE64->MD5获得 // 任务令牌 public string token { get; set; }//客户端生成一个UUID // 前置机编号 public string terminalId { get; set; } // 操作用户编号 public string optUserID { get; set; } public DataSourceVersionArg() { secretKey = ""; token = ""; terminalId = ""; optUserID = ""; } } public class FileVersions { public int file_count { get; set; } public long space_size { get; set; } public string task_id { get; set; } public string task_time { get; set; } public int total_count { get; set; } public string version { get; set; } public FileVersions() { file_count = new int(); space_size = new long(); task_id = ""; task_time = ""; total_count = new int(); version = ""; } } public class DataSourceVersion { public Scan datasourceConfig { get; set; } public string datasourceId { get; set; } public string datasourceName { get; set; } public int datasourceStatus { get; set; } public int datasourceType { get; set; } public List<FileVersions> versions { get; set; } public DataSourceVersion() { datasourceConfig = new Scan(); datasourceId = ""; datasourceName = ""; datasourceStatus = new int(); datasourceType = new int(); versions = new List<FileVersions>(); } } /// <summary> /// 查询数据源接口 /// </summary> public class DataSourceVersionQuery { public string code { get; set; } public string message { get; set; } public List<DataSourceVersion> datas { get; set; } public DataSourceVersionQuery() { code = ""; message = ""; datas = new List<DataSourceVersion>(); } } /// <summary> /// 数据源版本信息 /// </summary> public class DataSourceVersionDatas { public List<DataSourceVersion> datas { get; set; } public DataSourceVersionDatas() { datas = new List<DataSourceVersion>(); } } /// <summary> /// 文件恢复,文件信息查询 /// </summary> /// public class QueryFileInfoArg { // 通讯令牌 public string secretKey { get; set; }//由token进过MD5->BASE64->MD5获得 // 任务令牌 public string token { get; set; }//客户端生成一个UUID // 数据源编号 public string datasourceId { get; set; } // 操作用户编号 public string optUserID { get; set; } // 目录文件编号--如果为根目录使用 DS_ROOT public string fileID { get; set; } // 查询的版本编号 如果是综合分析 这个字段设置为 ALL public string taskID { get; set; } public QueryFileInfoArg() { secretKey = ""; token = ""; datasourceId = ""; optUserID = ""; fileID = ""; taskID = ""; } } public class FileInfoCondition { public string datasourceId { get; set; } public string parentId { get; set; } public string taskID { get; set; } public FileInfoCondition() { datasourceId = ""; parentId = ""; taskID = ""; } } public class FileInfo { // 文件唯一编号 public string file_id { get; set; } // 源相对目录 public string file_src_path { get; set; } // 文件名 public string file_name { get; set; } // 文件后缀 public string file_suffix { get; set; } // 是否为文件 public bool is_file { get; set; } // 上级文件编号 public string parent_id { get; set; } // 是否删除 public bool is_del { get; set; } // 是否隐藏 public bool is_hide { get; set; } // 文件大小 public int size { get; set; } // 文件创建时间 public string create_time { get; set; } // 文件创建人 public string create_user { get; set; } // 文件最后修改时间 public string lm_time { get; set; } // 文件最后修改人 public string lm_user { get; set; } // 是否可读 public bool can_read { get; set; } public FileInfo() { file_id = ""; file_src_path = ""; file_name = ""; file_suffix = ""; is_file = new bool(); parent_id = ""; is_del = new bool(); is_hide = new bool(); size = new int(); create_time = ""; create_user = ""; lm_time = ""; lm_user = ""; can_read = new bool(); } } public class FileInfoAndCondition { public FileInfoCondition condition { get; set; } public List<FileInfo> fileInfos { get; set; } public FileInfoAndCondition() { condition = new FileInfoCondition(); fileInfos = new List<FileInfo>(); } } /// <summary> /// 查询文件信息接口 /// </summary> public class FileInfoQuery { public string code { get; set; } public string message { get; set; } public FileInfoAndCondition datas { get; set; } public FileInfoQuery() { code = ""; message = ""; datas = new FileInfoAndCondition(); } } /// <summary> /// 文件信息 /// </summary> public class FileInfoData { public List<FileInfo> datas { get; set; } public FileInfoData() { datas = new List<FileInfo>(); } } public class QueryFileTrackArg { // 通讯令牌 public string secretKey { get; set; }//由token进过MD5->BASE64->MD5获得 // 任务令牌 public string token { get; set; }//客户端生成一个UUID // 文件编号 public string fileID { get; set; } // 操作用户编号 public string optUserID { get; set; } // 查询的版本编号 public string taskID { get; set; } public QueryFileTrackArg() { secretKey = ""; token = ""; fileID = ""; optUserID = ""; taskID = ""; } } public class FileTrack { // 文件操作 public string act_cmd { get; set; } // 是否可读 public bool can_read { get; set; } // 文件创建时间 public string create_time { get; set; } // 文件创建人 public string create_user { get; set; } // 是否删除 public bool is_del { get; set; } // 是否隐藏 public bool is_hide { get; set; } // 文件最后修改时间 public string lm_time { get; set; } // 文件最后修改人 public string lm_user { get; set; } // 文件大小 public int size { get; set; } public string taskID { get; set; } public FileTrack() { act_cmd = ""; can_read = new bool(); create_time = ""; create_user = ""; is_del = new bool(); is_hide = new bool(); lm_time = ""; lm_user = ""; size = new int(); taskID = ""; } } public class FileTrackCondition { public string fileID { get; set; } public string taskID { get; set; } public FileTrackCondition() { fileID = ""; taskID = ""; } } /// <summary> /// 查询文件轨迹接口 /// </summary> public class FileTrackQuery { public string code { get; set; } public string message { get; set; } public FileTrackCondition condition { get; set; } public List<FileTrack> datas { get; set; } public FileTrackQuery() { code = ""; message = ""; condition = new FileTrackCondition(); datas = new List<FileTrack>(); } } /// <summary> /// 文件轨迹 /// </summary> public class FileTrackData { public List<FileTrack> datas { get; set; } public FileTrackData() { datas = new List<FileTrack>(); } } /// <summary> /// 字典item /// </summary> public class DictionaryData { public string version { get; set; } public string task_time { get; set; } public DictionaryData() { version = ""; task_time = ""; } } public class FileRecoverArg { // 通讯令牌 public string secretKey { get; set; }//由token进过MD5->BASE64->MD5获得 // 任务令牌 public string token { get; set; }//客户端生成一个UUID // 操作用户编号 public string optUserID { get; set; } public string fileID { get; set; } public string taskID { get; set; } public string password { get; set; } public FileRecoverArg() { secretKey = ""; token = ""; optUserID = ""; fileID = ""; taskID = ""; password = ""; } } }

c#同步通信改异步,求代码如何修改?

using Newtonsoft.Json; using System; using System.Collections.Generic; using System.IO; using System.Linq; using System.Net; using System.Net.Sockets; using System.Text; using System.Threading.Tasks; namespace DAL { /// <summary> /// Socket接口 /// </summary> static class socket { //Socket private static Socket clientSocket; /// <summary> /// socket连接 /// </summary> /// <returns> /// true 成功 /// false 失败 /// </returns> public static bool SocketConnect() { //从配置文件获取IP string SocketIP = DAL.Common.ReadConfigString("Recover", "IP"); //从配置文件获取端口 int SocketPort = Convert.ToInt32(DAL.Common.ReadConfigString("Recover", "Port")); try { //创建socket实例 clientSocket = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp); //创建IP地址 IPAddress IP = IPAddress.Parse(SocketIP); //创建网络端点 IPEndPoint ipEnd = new IPEndPoint(IP, SocketPort); //clientSocket.Blocking = false; //Socket连接 clientSocket.Connect(ipEnd); if (clientSocket.Connected) { return true; } else { return false; } } catch (Exception e) { string strError = ""; strError += "\r\n SocketIP = " + SocketIP.ToString(); strError += "\r\n SocketPort = " + SocketPort.ToString(); DAL.Common.WriteErrorLog(e, strError); return false; } } /// <summary> /// Socket发送数据 /// </summary> /// <param name="strSend"> /// 数据的内容 /// </param> public static void SocketSend(string strSend) { try { Byte[] bytesSent = Encoding.UTF8.GetBytes(strSend); //按byte发送 clientSocket.Send(bytesSent, bytesSent.Length, 0); } catch (Exception e) { string strError = ""; DAL.Common.WriteErrorLog(e, strError); } } /// <summary> /// Socket接收数据 /// </summary> /// <returns> /// 收到的数据 /// </returns> public static string SocketReceive() { string result = ""; try { MemoryStream stream = new MemoryStream(); Byte[] bytesReceived = new Byte[256]; int bytes = 0; do { bytes = clientSocket.Receive(bytesReceived, bytesReceived.Length, 0); stream.Write(bytesReceived, 0, bytes); } while (bytes > 0); result = System.Text.Encoding.UTF8.GetString(stream.ToArray()); /*string strLogFile = System.AppDomain.CurrentDomain.BaseDirectory + "debug.txt"; StreamWriter sw = new StreamWriter(strLogFile, true); sw.WriteLine(result); sw.WriteLine("\n------------------------------------------------------------------------\n"); int len = stream.ToArray().Length; char[] tempchar = new char[len]; byte[] tempbyte = new byte[len]; tempbyte = stream.ToArray(); for (int i = 0; i < len; i++) { tempchar[i] = (char)tempbyte[i]; } sw.Write(tempchar); sw.WriteLine("\n------------------------------------------------------------------------\n"); sw.Flush(); sw.Close();*/ //接收完毕后断开连接 clientSocket.Close(); } catch (Exception e) { string strError = ""; DAL.Common.WriteErrorLog(e, strError); } return result; } /// <summary> /// Socket通信 /// </summary> /// <param name="strSend"> /// 发送的信息 /// </param> /// <returns> /// 包体的内容 /// </returns> public static string GetSocketData(string strSend) { string strDatas = ""; string strResult = ""; string strExtLength = ""; try { //Socket连接 SocketConnect(); //发送信息 SocketSend(strSend); //接收服务器的信息 strResult = SocketReceive(); //获取扩展信息的长度 strExtLength = strResult.Substring(16, 12); int ExtLength = Convert.ToInt32(strExtLength); //扩展信息,暂不使用 //string strExtInfo = strResult.Substring(32, ExtLength); //获取包体的内容 strDatas = strResult.Substring(ExtLength + 32); //strDatas = decodedString; } catch (Exception e) { string strError = ""; strError += "\r\n strResult = " + strResult; strError += "\r\n strExtLength = " + strExtLength; DAL.Common.WriteErrorLog(e, strError); strDatas = ""; } return strDatas; }

C++ socket端口复用的问题

环境 公网服务器1台,内网服务器若干。其中一台内网可以和公网连接通信,打算在公网上用socket做端口转发来实现访各台问内网的目的。功能已经实现了(一对一连接),但端口复用问题一直很困惑,请各位帮忙检查一下代码,谢谢 公网代码 ``` // 绑定两个服务器socket void bind2bind(int port1, int port2) { char msgbuf[100]; memset(msgbuf, 0, 100); sprintf(msgbuf, "[+] 服务器初始化...\r\n"); outprint(msgbuf, strlen(msgbuf)); int fd0, fd1, fd2; if ((fd0 = create_socket()) == 0) return; if ((fd1 = create_socket()) == 0) return; if ((fd2 = create_socket()) == 0) return; int port0 = 5501; if (create_server(fd0, port0) == 0) { closesocket(fd0); return; } sprintf(msgbuf, "[+] 成功监听通信端口: %d\r\n", port0); outprint(msgbuf, strlen(msgbuf)); // 创建第一个服务器 if (create_server(fd1, port1) == 0) { closesocket(fd1); return; } sprintf(msgbuf, "[+] 成功监听隧道端口: %d\r\n", port1); outprint(msgbuf, strlen(msgbuf)); // 创建第二个服务器 if (create_server(fd2, port2) == 0) { closesocket(fd2); return; } sprintf(msgbuf, "[+] 成功监听上线端口: %d\r\n", port2); outprint(msgbuf, strlen(msgbuf)); // 等待两端上线 while (1) { sprintf(msgbuf, "[%d] 正在建立通信端口: %d\r\n", idx, port0); outprint(msgbuf, strlen(msgbuf)); struct sockaddr_in client0; int size0 = sizeof(struct sockaddr); int sockfd0 = accept(fd0, (struct sockaddr *)&client0, &size0); sprintf(msgbuf, "[%d] 通信端口连接成功 IP地址: %s\r\n", idx, inet_ntoa(client0.sin_addr)); outprint(msgbuf, strlen(msgbuf)); sprintf(msgbuf, "[%d] 发送idx值: %d\r\n", idx, idx); outprint(msgbuf, strlen(msgbuf)); char idxbuf[10]; memset(idxbuf, 0, 10); sprintf(idxbuf, "%d", idx); int send0 = send(sockfd0, idxbuf, strlen(idxbuf)+1, 0); if (send0 <= 0) { closesocket(sockfd0); continue; } closesocket(sockfd0); sprintf(msgbuf, "[%d] 正在建立隧道端口: %d\r\n", idx, port1); outprint(msgbuf, strlen(msgbuf)); struct sockaddr_in client1; int size1 = sizeof(struct sockaddr); int sockfd1 = accept(fd1, (struct sockaddr *)&client1, &size1); sprintf(msgbuf, "[%d] 正在建立上线端口: %d\r\n", idx, port2); outprint(msgbuf, strlen(msgbuf)); struct sockaddr_in client2; int size2 = sizeof(struct sockaddr); int sockfd2 = accept(fd2, (struct sockaddr *)&client2, &size2); sprintf(msgbuf, "[%d] 通过上线端口连接成功 IP地址: %s\r\n", idx, inet_ntoa(client2.sin_addr)); outprint(msgbuf, strlen(msgbuf)); // socket transocket sock; sock.fd1 = sockfd1; sock.fd2 = sockfd2; sock.idx = idx; CreateThread(NULL, 0, (LPTHREAD_START_ROUTINE)transmitdata, (LPVOID)&sock, 0, NULL); idx++; } } ``` ``` 负责通信的内网代码 { int port0 = 5501; char msgbuf[100]; memset(msgbuf, 0, 100); while (1) { int sockfd0; if ((sockfd0 = create_socket()) == 0) return 0; // 通过5501端口连接服务器 sprintf(msgbuf, "[+] 正在连接服务器 %s:%d\r\n", sConnectHost, port0); outprint(msgbuf, strlen(msgbuf)); if (client_connect(sockfd0, sConnectHost, port0) == 0) { closesocket(sockfd0); continue; } sprintf(msgbuf, "[+] 服务器连接成功\r\n"); outprint(msgbuf, strlen(msgbuf)); // 接收服务器idx值 char idxbuf[10]; memset(idxbuf, 0, 10); int read0 = recv(sockfd0, idxbuf, 10, 0); if (read0 > 0) { // 在线程内执行conn2conn int nIdx = atoi(idxbuf); tranconn2conn conn; conn.host1 = sConnectHost; conn.port1 = iConnectPort; conn.host2 = sTransmitHost; conn.port2 = iTransmitPort; conn.idx = nIdx; CreateThread(NULL, 0, (LPTHREAD_START_ROUTINE)conn2conn, (LPVOID)&conn, 0, NULL); } } closeallfd(); } // 内网转发数据 void conn2conn(LPVOID data) { tranconn2conn *conn = (tranconn2conn *)data; char msgbuf[100]; memset(msgbuf, 0, 100); while (1) { int sockfd1, sockfd2; if ((sockfd1 = create_socket()) == 0) return; if ((sockfd2 = create_socket()) == 0) return; sprintf(msgbuf, "[%d] 正在连接服务器 %s:%d\r\n", conn->idx, conn->host1, conn->port1); outprint(msgbuf, strlen(msgbuf)); if (client_connect(sockfd1, conn->host1, conn->port1) == 0) { closesocket(sockfd1); closesocket(sockfd2); continue; } sprintf(msgbuf, "[%d] 服务器连接成功\r\n", conn->idx); outprint(msgbuf, strlen(msgbuf)); sprintf(msgbuf, "[%d] 正在连接内网 %s:%d\r\n", conn->idx, conn->host2, conn->port2); outprint(msgbuf, strlen(msgbuf)); if (client_connect(sockfd2, conn->host2, conn->port2) == 0) { closesocket(sockfd1); closesocket(sockfd2); continue; } sprintf(msgbuf, "[%d] 内网连接成功\r\n", conn->idx); outprint(msgbuf, strlen(msgbuf)); // socket transocket sock; sock.fd1 = sockfd1; sock.fd2 = sockfd2; sock.idx = conn->idx; transmitdata(&sock); } } ``` ``` 数据转发代码 // 服务器转发数据 void transmitdata(LPVOID data) { transocket *sock = (transocket *)data; // 准备采用select模型 fd_set readfd, writefd; char read_in1[MAXSIZE], send_out1[MAXSIZE]; char read_in2[MAXSIZE], send_out2[MAXSIZE]; struct sockaddr_in client1, client2; char host1[20], host2[20], msgbuf[100]; memset(host1, 0, 20); memset(host2, 0, 20); memset(msgbuf, 0, 100); int port1 = 0, port2 = 0; int structsize1 = sizeof(struct sockaddr); int structsize2 = sizeof(struct sockaddr); // 获取第一客户端信息 if (getpeername(sock->fd1, (struct sockaddr *)&client1, &structsize1) < 0) { strcpy(host1, "fd1"); } else { strcpy(host1, inet_ntoa(client1.sin_addr)); port1 = ntohs(client1.sin_port); } // 获取第二客户端信息 if (getpeername(sock->fd2, (struct sockaddr *)&client2, &structsize2) < 0) { strcpy(host2, "fd2"); } else { strcpy(host2, inet_ntoa(client2.sin_addr)); port2 = ntohs(client2.sin_port); } sprintf(msgbuf, "[%d] fd1: %d, fd2: %d\r\n", sock->idx, sock->fd1, sock->fd2); outprint(msgbuf, strlen(msgbuf)); // 输出两个客户端信息 sprintf(msgbuf, "[%d] 建立数据转发走向(%s:%d <-> %s:%d)\r\n", sock->idx, host1, port1, host2, port2); outprint(msgbuf, strlen(msgbuf)); // 最大检测数目 int maxfd = max(sock->fd1, sock->fd2) + 1; // 设置检测超时 struct timeval timeset; timeset.tv_sec = TIMEOUT; // 超时秒数 timeset.tv_usec = 0; // 超时微秒 // 位模式清零 memset(send_out1, 0, MAXSIZE); memset(send_out2, 0, MAXSIZE); // 可读长度 int totalread1 = 0, totalread2 = 0; while (1) { // 采用select异步模型 FD_ZERO(&readfd); FD_ZERO(&writefd); // 添加到fd集合 FD_SET(sock->fd1, &readfd); FD_SET(sock->fd1, &writefd); FD_SET(sock->fd2, &readfd); FD_SET(sock->fd2, &writefd); // 第一个参数会被系统忽略掉 int result = select(maxfd, &readfd, &writefd, NULL, &timeset); if ((result < 0) && (errno != EINTR)) { // 程序出错 sprintf(msgbuf, "[%d] Error: select函数出错\r\n", sock->idx); outprint(msgbuf, strlen(msgbuf)); break; } else if (result == 0) { // 等待超时 sprintf(msgbuf, "[%d] Error: select函数等待超时\r\n", sock->idx); outprint(msgbuf, strlen(msgbuf)); continue; } // fd1可读, 只要可读, 一次即可读取完整, 无需while循环 if (FD_ISSET(sock->fd1, &readfd) && totalread1 < MAXSIZE) { int read1 = recv(sock->fd1, read_in1, MAXSIZE - totalread1, 0); if (read1 == 0 || (read1 < 0 && errno != EINTR)) { sprintf(msgbuf, "[%d] Error: 读取fd1出错\r\n", sock->idx); outprint(msgbuf, strlen(msgbuf)); break; } // 改变fd1的发送缓冲区和他的大小(接了就要发嘛) memcpy(send_out1 + totalread1, read_in1, read1); sprintf(msgbuf, "[%d] fd1成功在地址: %16s:%d上面读取%d字节\r\n", sock->idx, host1, port1, read1); outprint(msgbuf, strlen(msgbuf)); totalread1 += read1; memset(read_in1, 0, MAXSIZE); } // fd2可写 if (FD_ISSET(sock->fd2, &writefd)) { int err = 0; int sendcount1 = 0; // 发送的话可能一次发不完(数据包过大) while (totalread1 > 0) { int send1 = send(sock->fd2, send_out1+sendcount1, totalread1, 0); if (send1 == 0 || (send1 < 0 && errno != EINTR)) { sprintf(msgbuf, "[%d] Error: 写入fd2出错\r\n", sock->idx); outprint(msgbuf, strlen(msgbuf)); err = 1; break; } if ((send1 < 0) && (errno == ENOSPC)) break; // 改变缓冲区大小 sendcount1 += send1; totalread1 -= send1; sprintf(msgbuf, "[%d] fd2成功在地址: %16s:%d上面发送%d字节\r\n", sock->idx, host2, port2, send1); outprint(msgbuf, strlen(msgbuf)); } // 检验出错 if (err == 1) break; // 如果发送了数据, 并且没有发送干净 if ((totalread1 > 0) && (sendcount1 > 0)) { // 理论上下面两行永远不会执行 memcpy(send_out1, send_out1 + sendcount1, totalread1); memset(send_out1 + totalread1, 0, MAXSIZE - totalread1); } else { memset(send_out1, 0, MAXSIZE); } } // fd2可读, 只要可读, 一次即可读取完整, 无需while循环 if (FD_ISSET(sock->fd2, &readfd) && totalread2 < MAXSIZE) { int read2 = recv(sock->fd2, read_in2, MAXSIZE - totalread2, 0); if (read2 == 0 || (read2 < 0 && errno != EINTR)) { sprintf(msgbuf, "[%d] Error: 读取fd2出错\r\n", sock->idx); outprint(msgbuf, strlen(msgbuf)); break; } // 接了就立即发出去 memcpy(send_out2 + totalread2, read_in2, read2); sprintf(msgbuf, "[%d] fd2成功在地址: %16s:%d上面读取%d字节\r\n", sock->idx, host2, port2, read2); outprint(msgbuf, strlen(msgbuf)); totalread2 += read2; memset(read_in2, 0, MAXSIZE); } // fd1可写 if (FD_ISSET(sock->fd1, &writefd)) { int err2 = 0; int sendcount2 = 0; while (totalread2 > 0) { int send2 = send(sock->fd1, send_out2 + sendcount2, totalread2, 0); if (send2 == 0 || (send2 < 0 && errno != EINTR)) { sprintf(msgbuf, "[%d] Error: 写入fd1出错\r\n", sock->idx); outprint(msgbuf, strlen(msgbuf)); err2 = 1; break; } if ((send2 < 0) && (errno == ENOSPC)) break; sendcount2 += send2; totalread2 -= send2; sprintf(msgbuf, "[%d] fd1成功在地址: %16s:%d上面发送%d字节\r\n", sock->idx, host1, port1, send2); outprint(msgbuf, strlen(msgbuf)); } if (err2 == 1) break; if ((totalread2 > 0) && (sendcount2 > 0)) { memcpy(send_out2, send_out2+sendcount2, totalread2); memset(send_out2 + totalread2, 0, MAXSIZE - totalread2); } else { memset(send_out2, 0, MAXSIZE); } } } // 关闭socket closesocket(sock->fd1); closesocket(sock->fd2); sprintf(msgbuf, "[%d] 成功关闭掉两个socket, fd1, fd2\r\n", sock->idx); outprint(msgbuf, strlen(msgbuf)); sprintf(msgbuf, "[%d] 本次数据转发结束\r\n\n", sock->idx); outprint(msgbuf, strlen(msgbuf)); } ```

SOCKET服务器编写一般是什么思路。

我编写的SOCKET感觉效率不高。求真实思路。有源代码最好 谢谢!

AsyncSocket异步TCP中,didReadData不接收数据

大家好,我遇到一个头痛的问题,我写的TCP异步客户端一直接收不到数据,请大大们指教。 我们的服务端,是用C#写的,TCP是长链接,始终用同一个链接发送和接收数据,服务端用别的程序测试是没问题的。 以下是我的代码: self.outSocket =[[AsyncSocket alloc]init]; self.outSocket.delegate =self ; if(![self.outSocket connectToHost:@"192.168.43.30" onPort:5220 error:&err]) { NSLog(@"Error: %@", err); } NSString * jsonString =[NSString stringWithFormat:@"{Action:\"GetActList\",PageIndex:\"1\",title:\"登山\",desctination:\"\",startCity:\"深圳\",theme:\"\",startTime:\"\",status:\"\",actType:\"AA\",sort:\"create\"}"]; NSData *data =[jsonString dataUsingEncoding:NSUTF8StringEncoding]; [self.outSocket writeData:data withTimeout:-1 tag:0]; [self.outSocket readDataToData:[AsyncSocket CRLFData] withTimeout:-1 tag:0]; -(void)onSocket:(AsyncSocket *)sock didReadData:(NSData *)data withTag:(long)tag{ NSLog(@"%d",data.length); NSString * sting =[[NSString alloc]initWithData:data encoding:NSUTF8StringEncoding]; NSLog(@"%@",sting); } - (void)onSocket:(AsyncSocket *)sock didReadPartialDataOfLength:(NSUInteger)partialLength tag:(long)tag{ NSLog(@"Received bytes: %d",partialLength); } didReadPartialDataOfLength 这个可以接收到。 didReadData 始终不执行,接收不到数据,看说明,是要读完请求数据到内存才调用,请问,它的读完是怎么来识别呢?

在中国程序员是青春饭吗?

今年,我也32了 ,为了不给大家误导,咨询了猎头、圈内好友,以及年过35岁的几位老程序员……舍了老脸去揭人家伤疤……希望能给大家以帮助,记得帮我点赞哦。 目录: 你以为的人生 一次又一次的伤害 猎头界的真相 如何应对互联网行业的「中年危机」 一、你以为的人生 刚入行时,拿着傲人的工资,想着好好干,以为我们的人生是这样的: 等真到了那一天,你会发现,你的人生很可能是这样的: ...

程序员请照顾好自己,周末病魔差点一套带走我。

程序员在一个周末的时间,得了重病,差点当场去世,还好及时挽救回来了。

C++(数据结构与算法)78:---分而治之

一、分而治之的思想 分而治之方法与软件设计的模块化方法非常相似 分而治之通常不用于解决问题的小实例,而要解决一个问题的大实例。一般步骤为: ①把一个大实例分为两个或多个更小的实例 ②分别解决每个小实例 ③把这些小实例的解组合成原始大实例的解 二、实际应用之找出假币 问题描述 一个袋子有16个硬币,其中只有一个是假币,这个假币比其他的真币重量轻(其他所有真币的重量都是相同的)...

springboot+jwt实现token登陆权限认证

一 前言 此篇文章的内容也是学习不久,终于到周末有时间码一篇文章分享知识追寻者的粉丝们,学完本篇文章,读者将对token类的登陆认证流程有个全面的了解,可以动态搭建自己的登陆认证过程;对小项目而已是个轻量级的认证机制,符合开发需求;更多精彩原创内容关注公主号知识追寻者,读者的肯定,就是对作者的创作的最大支持; 二 jwt实现登陆认证流程 用户使用账号和面发出post请求 服务器接受到请求后使用私...

技术大佬:我去,你写的 switch 语句也太老土了吧

昨天早上通过远程的方式 review 了两名新来同事的代码,大部分代码都写得很漂亮,严谨的同时注释也很到位,这令我非常满意。但当我看到他们当中有一个人写的 switch 语句时,还是忍不住破口大骂:“我擦,小王,你丫写的 switch 语句也太老土了吧!” 来看看小王写的代码吧,看完不要骂我装逼啊。 private static String createPlayer(PlayerTypes p...

win10暴力查看wifi密码

刚才邻居打了个电话说:喂小灰,你家wifi的密码是多少,我怎么连不上了。 我。。。 我也忘了哎,就找到了一个好办法,分享给大家: 第一种情况:已经连接上的wifi,怎么知道密码? 打开:控制面板\网络和 Internet\网络连接 然后右击wifi连接的无线网卡,选择状态 然后像下图一样: 第二种情况:前提是我不知道啊,但是我以前知道密码。 此时可以利用dos命令了 1、利用netsh wlan...

女程序员,为什么比男程序员少???

昨天看到一档综艺节目,讨论了两个话题:(1)中国学生的数学成绩,平均下来看,会比国外好?为什么?(2)男生的数学成绩,平均下来看,会比女生好?为什么?同时,我又联想到了一个技术圈经常讨...

副业收入是我做程序媛的3倍,工作外的B面人生是怎样的?

提到“程序员”,多数人脑海里首先想到的大约是:为人木讷、薪水超高、工作枯燥…… 然而,当离开工作岗位,撕去层层标签,脱下“程序员”这身外套,有的人生动又有趣,马上展现出了完全不同的A/B面人生! 不论是简单的爱好,还是正经的副业,他们都干得同样出色。偶尔,还能和程序员的特质结合,产生奇妙的“化学反应”。 @Charlotte:平日素颜示人,周末美妆博主 大家都以为程序媛也个个不修边幅,但我们也许...

MySQL数据库面试题(2020最新版)

文章目录数据库基础知识为什么要使用数据库什么是SQL?什么是MySQL?数据库三大范式是什么mysql有关权限的表都有哪几个MySQL的binlog有有几种录入格式?分别有什么区别?数据类型mysql有哪些数据类型引擎MySQL存储引擎MyISAM与InnoDB区别MyISAM索引与InnoDB索引的区别?InnoDB引擎的4大特性存储引擎选择索引什么是索引?索引有哪些优缺点?索引使用场景(重点)...

如果你是老板,你会不会踢了这样的员工?

有个好朋友ZS,是技术总监,昨天问我:“有一个老下属,跟了我很多年,做事勤勤恳恳,主动性也很好。但随着公司的发展,他的进步速度,跟不上团队的步伐了,有点...

我入职阿里后,才知道原来简历这么写

私下里,有不少读者问我:“二哥,如何才能写出一份专业的技术简历呢?我总感觉自己写的简历太烂了,所以投了无数份,都石沉大海了。”说实话,我自己好多年没有写过简历了,但我认识的一个同行,他在阿里,给我说了一些他当年写简历的方法论,我感觉太牛逼了,实在是忍不住,就分享了出来,希望能够帮助到你。 01、简历的本质 作为简历的撰写者,你必须要搞清楚一点,简历的本质是什么,它就是为了来销售你的价值主张的。往深...

程序员写出这样的代码,能不挨骂吗?

当你换槽填坑时,面对一个新的环境。能够快速熟练,上手实现业务需求是关键。但是,哪些因素会影响你快速上手呢?是原有代码写的不够好?还是注释写的不够好?昨夜...

带了6个月的徒弟当了面试官,而身为高级工程师的我天天修Bug......

即将毕业的应届毕业生一枚,现在只拿到了两家offer,但最近听到一些消息,其中一个offer,我这个组据说客户很少,很有可能整组被裁掉。 想问大家: 如果我刚入职这个组就被裁了怎么办呢? 大家都是什么时候知道自己要被裁了的? 面试软技能指导: BQ/Project/Resume 试听内容: 除了刷题,还有哪些技能是拿到offer不可或缺的要素 如何提升面试软实力:简历, 行为面试,沟通能...

优雅的替换if-else语句

场景 日常开发,if-else语句写的不少吧??当逻辑分支非常多的时候,if-else套了一层又一层,虽然业务功能倒是实现了,但是看起来是真的很不优雅,尤其是对于我这种有强迫症的程序"猿",看到这么多if-else,脑袋瓜子就嗡嗡的,总想着解锁新姿势:干掉过多的if-else!!!本文将介绍三板斧手段: 优先判断条件,条件不满足的,逻辑及时中断返回; 采用策略模式+工厂模式; 结合注解,锦...

!大部分程序员只会写3年代码

如果世界上都是这种不思进取的软件公司,那别说大部分程序员只会写 3 年代码,恐怕就没有程序员这种职业。

离职半年了,老东家又发 offer,回不回?

有小伙伴问松哥这个问题,他在上海某公司,在离职了几个月后,前公司的领导联系到他,希望他能够返聘回去,他很纠结要不要回去? 俗话说好马不吃回头草,但是这个小伙伴既然感到纠结了,我觉得至少说明了两个问题:1.曾经的公司还不错;2.现在的日子也不是很如意。否则应该就不会纠结了。 老实说,松哥之前也有过类似的经历,今天就来和小伙伴们聊聊回头草到底吃不吃。 首先一个基本观点,就是离职了也没必要和老东家弄的苦...

2020阿里全球数学大赛:3万名高手、4道题、2天2夜未交卷

阿里巴巴全球数学竞赛( Alibaba Global Mathematics Competition)由马云发起,由中国科学技术协会、阿里巴巴基金会、阿里巴巴达摩院共同举办。大赛不设报名门槛,全世界爱好数学的人都可参与,不论是否出身数学专业、是否投身数学研究。 2020年阿里巴巴达摩院邀请北京大学、剑桥大学、浙江大学等高校的顶尖数学教师组建了出题组。中科院院士、美国艺术与科学院院士、北京国际数学...

为什么你不想学习?只想玩?人是如何一步一步废掉的

不知道是不是只有我这样子,还是你们也有过类似的经历。 上学的时候总有很多光辉历史,学年名列前茅,或者单科目大佬,但是虽然慢慢地长大了,你开始懈怠了,开始废掉了。。。 什么?你说不知道具体的情况是怎么样的? 我来告诉你: 你常常潜意识里或者心理觉得,自己真正的生活或者奋斗还没有开始。总是幻想着自己还拥有大把时间,还有无限的可能,自己还能逆风翻盘,只不是自己还没开始罢了,自己以后肯定会变得特别厉害...

男生更看重女生的身材脸蛋,还是思想?

往往,我们看不进去大段大段的逻辑。深刻的哲理,往往短而精悍,一阵见血。问:产品经理挺漂亮的,有点心动,但不知道合不合得来。男生更看重女生的身材脸蛋,还是...

为什么程序员做外包会被瞧不起?

二哥,有个事想询问下您的意见,您觉得应届生值得去外包吗?公司虽然挺大的,中xx,但待遇感觉挺低,马上要报到,挺纠结的。

当HR压你价,说你只值7K,你该怎么回答?

当HR压你价,说你只值7K时,你可以流畅地回答,记住,是流畅,不能犹豫。 礼貌地说:“7K是吗?了解了。嗯~其实我对贵司的面试官印象很好。只不过,现在我的手头上已经有一份11K的offer。来面试,主要也是自己对贵司挺有兴趣的,所以过来看看……”(未完) 这段话主要是陪HR互诈的同时,从公司兴趣,公司职员印象上,都给予对方正面的肯定,既能提升HR的好感度,又能让谈判气氛融洽,为后面的发挥留足空间。...

面试:第十六章:Java中级开发

HashMap底层实现原理,红黑树,B+树,B树的结构原理 Spring的AOP和IOC是什么?它们常见的使用场景有哪些?Spring事务,事务的属性,传播行为,数据库隔离级别 Spring和SpringMVC,MyBatis以及SpringBoot的注解分别有哪些?SpringMVC的工作原理,SpringBoot框架的优点,MyBatis框架的优点 SpringCould组件有哪些,他们...

早上躺尸,晚上干活:硅谷科技公司这么流行迟到?

硅谷科技公司上班时间OPEN早已不是什么新鲜事,早九晚五是常态,但有很多企业由于不打卡,员工们10点、11点才“姗姗来迟”的情况也屡见不鲜。 这种灵活的考勤制度为人羡慕,甚至近年来,国内某些互联网企业也纷纷效仿。不过,硅谷普遍弹性的上班制度是怎么由来的呢?这种“流行性迟到”真的有那么轻松、悠哉吗? 《动态规划专题班》 课程试听内容: 动态规划的解题要领 动态规划三大类 求最值/计数/可行性 常...

面试阿里p7,被按在地上摩擦,鬼知道我经历了什么?

面试阿里p7被问到的问题(当时我只知道第一个):@Conditional是做什么的?@Conditional多个条件是什么逻辑关系?条件判断在什么时候执...

Python爬虫,高清美图我全都要(彼岸桌面壁纸)

爬取彼岸桌面网站较为简单,用到了requests、lxml、Beautiful Soup4

无代码时代来临,程序员如何保住饭碗?

编程语言层出不穷,从最初的机器语言到如今2500种以上的高级语言,程序员们大呼“学到头秃”。程序员一边面临编程语言不断推陈出新,一边面临由于许多代码已存在,程序员编写新应用程序时存在重复“搬砖”的现象。 无代码/低代码编程应运而生。无代码/低代码是一种创建应用的方法,它可以让开发者使用最少的编码知识来快速开发应用程序。开发者通过图形界面中,可视化建模来组装和配置应用程序。这样一来,开发者直...

面试了一个 31 岁程序员,让我有所触动,30岁以上的程序员该何去何从?

最近面试了一个31岁8年经验的程序猿,让我有点感慨,大龄程序猿该何去何从。

大三实习生,字节跳动面经分享,已拿Offer

说实话,自己的算法,我一个不会,太难了吧

程序员垃圾简历长什么样?

已经连续五年参加大厂校招、社招的技术面试工作,简历看的不下于万份 这篇文章会用实例告诉你,什么是差的程序员简历! 疫情快要结束了,各个公司也都开始春招了,作为即将红遍大江南北的新晋UP主,那当然要为小伙伴们做点事(手动狗头)。 就在公众号里公开征简历,义务帮大家看,并一一点评。《启舰:春招在即,义务帮大家看看简历吧》 一石激起千层浪,三天收到两百多封简历。 花光了两个星期的所有空闲时...

Java岗开发3年,公司临时抽查算法,离职后这几题我记一辈子

前几天我们公司做了一件蠢事,非常非常愚蠢的事情。我原以为从学校出来之后,除了找工作有测试外,不会有任何与考试有关的事儿。 但是,天有不测风云,公司技术总监、人事总监两位大佬突然降临到我们事业线,叫上我老大,给我们组织了一场别开生面的“考试”。 那是一个风和日丽的下午,我翘着二郎腿,左手端着一杯卡布奇诺,右手抓着我的罗技鼠标,滚动着轮轴,穿梭在头条热点之间。 “淡黄的长裙~蓬松的头发...

立即提问
相关内容推荐