我在计算机和服务器之间的Socket通信时遇到问题。只有当我点击一个特定的按钮时,才会通过套接字建立通信。在第一次沟通中,一切都完美无缺。如果我再次单击,则不执行代码。我放了一个断点来看看发生了什么,并且看到在给定的线上,他只是试图执行该线,但很长一段时间。 (我总是传递相同的参数)。
长时间处理的行
serverStream.Read(inStream, 0, (int)clientSocket.ReceiveBufferSize);
客户代码
private void Form1_Load(object sender, EventArgs e)
{
msg("Client Started");
clientSocket.Connect("server_ip", 8855);
//clientSocket.Connect("127.0.0.1", 8873);
label1.Text = "Client Socket Program - Server Connected ...";
this.imprimir();
}
protected void imprimir()
{
NetworkStream serverStream = clientSocket.GetStream();
byte[] inStream = new byte[10025];
//// LINE THAT PROCESS FOR A LONG TIME IN THE SECOND TIME.
serverStream.Read(inStream, 0, (int)clientSocket.ReceiveBufferSize);
string returndata = System.Text.Encoding.ASCII.GetString(inStream);
int ponto = returndata.IndexOf('.');
returndata = returndata.Substring(0, ponto);
string[] quebraretorno = returndata.Split(';');
ServiceReference1.bematechSoapClient bema = new ServiceReference1.bematechSoapClient();
string r = bema.InformacoesImovelBematech(quebraretorno[0], quebraretorno[1]);
int retorno = -1;
retorno = IniciaPorta("COM7");
if (retorno == 1)
{
ConfiguraModeloImpressora(7);
BematechTX(r);
AcionaGuilhotina(1);
FechaPorta();
}
clientSocket.Close();
}
服务器代码
public void btnImprimeBematech_Locacao()
{
Utilidade.QuebraToken tk = new Utilidade.QuebraToken();
int Credenciada = Convert.ToInt32(tk.CarregaToken(1, HttpContext.Current.Request.Cookies["token"].Value));
TcpListener serverSocket = new TcpListener(8855);
int requestCount = 0;
TcpClient clientSocket = default(TcpClient);
serverSocket.Start();
clientSocket = serverSocket.AcceptTcpClient();
requestCount = 0;
while ((true))
{
try
{
requestCount = requestCount + 1;
NetworkStream networkStream = clientSocket.GetStream();
string serverResponse = Request.QueryString["id"] + ";" + Credenciada.ToString() + ".";
Byte[] sendBytes = Encoding.ASCII.GetBytes(serverResponse);
networkStream.Write(sendBytes, 0, sendBytes.Length);
networkStream.Flush();
}
catch (Exception ex)
{
}
}
clientSocket.Close();
serverSocket.Stop();
}
任何人都可以帮助我吗?
答案 0 :(得分:2)
似乎在第一次通信时,服务器接受一个新套接字并进入while循环。但是在第二次通信期间,它不会返回到serverSocket.AcceptTCPClient(),即不会退出while循环并且不接受任何新套接字。
您需要编辑服务器端代码,以便在当前连接的套接字断开连接时(仅添加另一个循环)返回到AcceptTCPClient()。并且您需要为已有的While循环提供退出条件。
TcpClient clientSocket = default(TcpClient);
serverSocket.Start();
while(True)
{
clientSocket = serverSocket.AcceptTcpClient()
requestCount = 0;
while ((clientSocket.Connected == true))
{
try
{
requestCount = requestCount + 1;
NetworkStream networkStream = clientSocket.GetStream();
string serverResponse = Request.QueryString["id"] + ";" + Credenciada.ToString() + ".";
Byte[] sendBytes = Encoding.ASCII.GetBytes(serverResponse);
networkStream.Write(sendBytes, 0, sendBytes.Length);
networkStream.Flush();
}
catch (Exception ex) { }
}
}