1

I have a server (written in java) that listens for a connection on a specific port. I have a client (written in c#) that connects with java server and try to send some data but the connection get reset with following error at server side. "java.net.SocketException: Connection reset"

Below is the client side code:-

 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();
        }
    }

Can anyone point me what am i doing wrong in this code that my connection is getting reset?

One more finding in code is that while I debug to this line, it should write the data in stream and server should receive it but nothing happens:-

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

Executing below lines will throws "java.net.SocketException: Connection reset" on server side.

serverStream.Flush();
serverStream.Close();
2
  • Can you show me how clientSocket got initialized? Commented Nov 25, 2014 at 8:06
  • Let me add the code in above question Commented Nov 25, 2014 at 10:05

2 Answers 2

0

You get this error when sending, not when connecting. It happens when you send to a connection that has already been closed by the peer, among other much less likely scenarios.

For example:

  1. You send something that the peer didn't understand; it closes the connection; you keep writing; this is what happens next.

Or

  1. The peer is sending something to you that you should be reading and you aren't, because you have already closed the socket.

Check the application protocol.

Sign up to request clarification or add additional context in comments.

1 Comment

I have gone through several related answer but unable to figure out this on my above mentioned code. I have even tried out using TELNET and it worked fine connecting on the designated IP and Port.
0

The original issue was in My Dotnet Client code the socket was close immediate after establishing. For this I have use the http://www.codeproject.com/Articles/19071/Quick-tool-A-minimalistic-Telnet-library

Below is the code that solved my problem

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;
                }
            }
        }
    }
}

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.