接收" java.net.SocketException:连接重置"从dotnet客户端连接到java服务器时

时间:2014-11-25 08:02:06

标签: java .net sockets

我有一个服务器(用java编写),用于侦听特定端口上的连接。 我有一个客户端(用c#编写)连接到java服务器并尝试发送一些数据但是连接在服务器端被重置并跟随错误。 " java.net.SocketException:连接重置"

以下是客户端代码: -

 public void ConnectServer()
    {
        try
        {
            if (Connect())
            {
                Broadcast("check");
            }
        }
        catch (Exception ex)
        {
            Logger.Text = ex.Message;
        }
    }

    private bool Connect()
    {
        bool flag = false;
        try
        {
            if (!clientSocket.Connected)
            {
              clientSocket.Connect(ConfigurationManager.AppSettings["SMSRequestNotifierServer"].ToString(), Convert.ToInt32(ConfigurationManager.AppSettings["SMSRequestNotifierPort"].ToString()));
                clientSocket.LingerState = new LingerOption(true,10);
                isConnected = true;
                flag = true;
            }
            else
            {
                flag = true;
            }
        }
        catch (Exception ex)
        {
            Logger.Text = ex.Message;
            flag = false;            }

        return flag;
    }

    private void Broadcast(String msg)
    {
        using (NetworkStream serverStream = clientSocket.GetStream())
        {
            byte[] outStream = System.Text.Encoding.ASCII.GetBytes(msg);
            serverStream.Write(outStream, 0, outStream.Length);
            serverStream.Flush();
            serverStream.Close();
            serverStream.Dispose();
            clientSocket.Close();
        }
    }

有人能指出我在这段代码中我的错误是什么,我的连接正在重置?

代码中的另一个发现是,当我调试到这一行时,它应该在流中写入数据,服务器应该接收它但没有任何反应: -

serverStream.Write(outStream, 0, outStream.Length);

执行以下行将抛出" java.net.SocketException:连接重置"在服务器端。

serverStream.Flush();
serverStream.Close();

2 个答案:

答案 0 :(得分:0)

发送时出现此错误,未连接时出现此错误。当您发送到已经被对等方关闭的连接时,会发生这种情况,以及其他可能性较小的情况。

例如:

  1. 你发送了一些同行并不理解的东西;它关闭了连接;你继续写作;接下来会发生这种情况。
    1. 对等方正在向发送一些您应该阅读的内容而且您不会,因为您已经关闭了套接字。
    2. 检查应用程序协议。

答案 1 :(得分:0)

最初的问题是在我的Dotnet客户端代码中,套接字在建立后立即关闭。 为此,我使用了 http://www.codeproject.com/Articles/19071/Quick-tool-A-minimalistic-Telnet-library

以下是解决我问题的代码

TelnetConnection oTelnetConnection = new TelnetConnection(ConfigurationManager.AppSettings["SMSRequestNotifierServer"].ToString(), Convert.ToInt32(ConfigurationManager.AppSettings["SMSRequestNotifierPort"].ToString()));
Logger.Text += oTelnetConnection.Read();
oTelnetConnection.WriteLine("check");



// minimalistic telnet implementation
// conceived by Tom Janssens on 2007/06/06  for codeproject
//
// http://www.corebvba.be



using System;
using System.Collections.Generic;
using System.Text;
using System.Net.Sockets;

namespace MinimalisticTelnet
{
    enum Verbs {
        WILL = 251,
        WONT = 252,
        DO = 253,
        DONT = 254,
        IAC = 255
    }

    enum Options
    {
        SGA = 3
    }

    class TelnetConnection
    {
        TcpClient tcpSocket;

        int TimeOutMs = 100;

        public TelnetConnection(string Hostname, int Port)
        {
            tcpSocket = new TcpClient(Hostname, Port);

        }

        public string Login(string Username,string Password,int LoginTimeOutMs)
        {
            int oldTimeOutMs = TimeOutMs;
            TimeOutMs = LoginTimeOutMs;
            string s = Read();
            if (!s.TrimEnd().EndsWith(":"))
               throw new Exception("Failed to connect : no login prompt");
            WriteLine(Username);

            s += Read();
            if (!s.TrimEnd().EndsWith(":"))
                throw new Exception("Failed to connect : no password prompt");
            WriteLine(Password);

            s += Read();
            TimeOutMs = oldTimeOutMs;
            return s;
        }

        public void WriteLine(string cmd)
        {
            Write(cmd + "\n");
        }

        public void Write(string cmd)
        {
            if (!tcpSocket.Connected) return;
            byte[] buf = System.Text.ASCIIEncoding.ASCII.GetBytes(cmd.Replace("\0xFF","\0xFF\0xFF"));
            tcpSocket.GetStream().Write(buf, 0, buf.Length);
        }

        public string Read()
        {
            if (!tcpSocket.Connected) return null;
            StringBuilder sb=new StringBuilder();
            do
            {
                ParseTelnet(sb);
                System.Threading.Thread.Sleep(TimeOutMs);
            } while (tcpSocket.Available > 0);
            return sb.ToString();
        }

        public bool IsConnected
        {
            get { return tcpSocket.Connected; }
        }

        void ParseTelnet(StringBuilder sb)
        {
            while (tcpSocket.Available > 0)
            {
                int input = tcpSocket.GetStream().ReadByte();
                switch (input)
                {
                    case -1 :
                        break;
                    case (int)Verbs.IAC:
                        // interpret as command
                        int inputverb = tcpSocket.GetStream().ReadByte();
                        if (inputverb == -1) break;
                        switch (inputverb)
                        {
                            case (int)Verbs.IAC: 
                                //literal IAC = 255 escaped, so append char 255 to string
                                sb.Append(inputverb);
                                break;
                            case (int)Verbs.DO: 
                            case (int)Verbs.DONT:
                            case (int)Verbs.WILL:
                            case (int)Verbs.WONT:
                                // reply to all commands with "WONT", unless it is SGA (suppres go ahead)
                                int inputoption = tcpSocket.GetStream().ReadByte();
                                if (inputoption == -1) break;
                                tcpSocket.GetStream().WriteByte((byte)Verbs.IAC);
                                if (inputoption == (int)Options.SGA )
                                    tcpSocket.GetStream().WriteByte(inputverb == (int)Verbs.DO ? (byte)Verbs.WILL:(byte)Verbs.DO); 
                                else
                                    tcpSocket.GetStream().WriteByte(inputverb == (int)Verbs.DO ? (byte)Verbs.WONT : (byte)Verbs.DONT); 
                                tcpSocket.GetStream().WriteByte((byte)inputoption);
                                break;
                            default:
                                break;
                        }
                        break;
                    default:
                        sb.Append( (char)input );
                        break;
                }
            }
        }
    }
}