在线等!关于Socket客户端一次连接,多次发送问题?
问题是:
现在用Socket做通讯,服务器那边一直在监听,客户端每发送一次数据前要先Connect一下服务器,然后Send数据,Send完了之后,都要Shutdown和Close一下,这样服务器会接受到一条来自客户端的消息,但是如果我Send之后,不做Shutdown和Close操作,继续用先前Connect之后的Socket实例直接Send的话,服务会收不到我的消息,所以现在我没发送一次都要Connect和Close一下,请问这个是什么原因啊?如何解决Connect一次,可以多次发送的问题呢?谢谢。
我的相关代码如下:
客户端:
using System;
using System.Net;
using System.Net.Sockets;
using System.Text;
namespace KBSSimulateServer.Common
{
public class MiniSocketClient
{
private IPAddress m_ipaServerIp;
private int m_nPort = 0;
private IPEndPoint ipepServer;
public MiniSocketClient(string strIpAddress, int nPort)
{
m_ipaServerIp = IPAddress.Parse(strIpAddress);
m_nPort = nPort;
}
public void TestConnect()
{
IPEndPoint ipepServer = new IPEndPoint(m_ipaServerIp, m_nPort);
Socket sktClient = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp);
sktClient.Connect(ipepServer);
sktClient.Shutdown(SocketShutdown.Both);
sktClient.Close();
}
public void SendAndReceive(string strSend, BaseForm frmBase, Port enmPort)
{
int nBytes = 0;
try
{
ipepServer = new IPEndPoint(m_ipaServerIp, m_nPort);
Socket sktClient = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp);
sktClient.Connect(ipepServer);
Byte[] bytSend = Encoding.ASCII.GetBytes(strSend);
nBytes = sktClient.Send(bytSend);
frmBase.PrintLog( "Send: " + Encoding.ASCII.GetString(bytSend, 0, nBytes), enmPort);
DateTime dtTime = DateTime.Now.AddSeconds(10.0);
Byte[] bytReceive = new Byte[1024];;
while (DateTime.Now < dtTime)
{
nBytes = sktClient.Receive(bytReceive, bytReceive.Length, 0);
frmBase.PrintLog( "Receive: " + Encoding.ASCII.GetString(bytReceive, 0, nBytes), enmPort);
if (nBytes > 0)
{
break;
}
}
sktClient.Shutdown(SocketShutdown.Both);
sktClient.Close();
}
catch (System.Exception e)
{
throw e;
}
}
}
}
[解决办法]
是你服务端的逻辑有问题!你要修改你的服务端代码!不过客户端也不是这样写的!
你去看看我的Blog里面的文章吧,里面有同步的,异步的!
http://wzd24.cnblogs.com