Click here to Skip to main content
Rate this: bad
good
Please Sign up or sign in to vote.
A Java Android App from an Android 2.2 phone, is sending string data to the C# program. The C# program receiving the data and showing it correctly for the first time only. Then it is not stopping receiving data. But since there is not data, it is showing as 0 as received data, while debugging and not receiving data which is sent second time by the Java App.
 
First I thought, may be Java app is sending data continuously. But C# program is receiving data even though the Java App has closed.
 
Full source code of C# program is at below:
using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.Linq;
using System.Net;
using System.Net.Sockets;
using System.Text;
using System.Windows.Forms;
    
namespace Network_IM
{
    public partial class Server : Form
    {
        public Socket listnerSocket;
        public Socket workerSocket;
        public AsyncCallback workerAsyncCallBack;
 
        //As a Client
        Socket clientSocket;
 
        public Server()
        {
            InitializeComponent();
            OnLoad();
            RegisterEvents();
        }
 
        private void RegisterEvents()
        {
            button1.Click += new EventHandler(button1_Click);
            txtInput.KeyDown += new KeyEventHandler(txtInput_KeyDown);
        }
    
        void txtInput_KeyDown(object sender, KeyEventArgs e)
        {
            if(e.KeyCode == Keys.Enter)
                button1_Click(null, null);
        }
   
        void button1_Click(object sender, EventArgs e)
        {
            try
            {
                clientSocket = new Socket(AddressFamily.InterNetwork,  SocketType.Stream, ProtocolType.Tcp);
                clientSocket.Connect(IPAddress.Parse("192.168.1.5"), 8222);
                clientSocket.Send(Encoding.UTF8.GetBytes(txtInput.Text));
                clientSocket.Close();
                txtLog.Text += " | Me: " + txtInput.Text + " | ";
                txtInput.Clear();
                txtInput.Focus();
            }
            catch (Exception ex)
            {
                MessageBox.Show(ex.Message);
            }
        }
  
        private void OnLoad()
        {
            try
            {
                IPEndPoint ipLocal = new IPEndPoint(IPAddress.Any, 8221);
                listnerSocket = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp);
                listnerSocket.Bind(ipLocal);
                listnerSocket.Listen(4);
                listnerSocket.BeginAccept(new AsyncCallback(OnClientConnect), null);
            }
            catch (SocketException se)
            {
                MessageBox.Show(se.Message);
            }
        }
  
        public void OnClientConnect(IAsyncResult asyn)
        {
            try
            {
                workerSocket = listnerSocket.EndAccept(asyn);
                WaitForData(workerSocket);
            }
            catch (ObjectDisposedException)
            {
                Debugger.Log(0, "1", "\n OnClientConnection: Socket has been closed\n");
            }
            catch (SocketException se)
            {
                MessageBox.Show(se.Message);
            }
        }
   
        private void WaitForData(Socket workerSoc)
        {
            try
            {
                if (workerAsyncCallBack == null)
                    workerAsyncCallBack = new AsyncCallback(OnDataReceived);
                CSocketPacket theSocPkt = new CSocketPacket();
                theSocPkt.thisSocket = workerSoc;
                workerSoc.BeginReceive(theSocPkt.dataBuffer, 0, theSocPkt.dataBuffer.Length, SocketFlags.None, workerAsyncCallBack, theSocPkt);
            }
            catch (SocketException se)
            {
                MessageBox.Show(se.Message);
            }
        }
    
        public void OnDataReceived(IAsyncResult asyn)
        {
            try
            {
                CSocketPacket theSockId = (CSocketPacket)asyn.AsyncState;
                int iRx = theSockId.thisSocket.EndReceive(asyn);
                char[] chars = new char[iRx + 1];
                Encoding.UTF8.GetDecoder().GetChars(theSockId.dataBuffer, 0, iRx, chars, 0);
                String szData = new String(chars);
                setTxtLogText(szData);
                WaitForData(workerSocket);
            }
            catch (ObjectDisposedException)
            {
                Debugger.Log(0, "1", "\nOnDataReceived: Socket has been closed\n");
            }
            catch (SocketException se)
            {
                MessageBox.Show(se.Message);
            }
        }
 
        delegate void setTxtLogTextDelegate(string newText);
 
        private void setTxtLogText(string newText)
        {
            try
            {
                if (txtLog.InvokeRequired)
                {
                    setTxtLogTextDelegate txtLogDelegate = new setTxtLogTextDelegate(setTxtLogText);
                    if (newText != "\0")
                        txtLog.Invoke(txtLogDelegate, new object[] { newText });
                }
                else
                    txtLog.Text += newText.Remove(1);
            }
            catch (Exception ex)
            { throw ex; }
        }
    }
 
    public class CSocketPacket
    {
        public Socket thisSocket;
        public byte[] dataBuffer = new byte[1];
    }
}
I am getting crazy going through the source code over and over again. Please help me. Smile | :)
Posted 3-Mar-12 1:32am

1 solution

Rate this: bad
good
Please Sign up or sign in to vote.

Solution 1

Hi there,
 
Your code is all good so far as I can see except you've missed a vital line. After calling end accept you do not call begin accept again. since your button click event tries to create a new connection each time, the second connection fails to connect. After end accept you need to call begin accept again. then your code should work.
 
Hope this helps,
Ed
  Permalink  
v3
Comments
iKrshnan at 5-Mar-12 6:30am
   
Thanks @Ed, it worked. Your answer is helped me very much. But there was another missing point, which I got resolved from <a href="http://stackoverflow.com/a/9546493/844071">here</a>. I think how dump I am that I did not thought even simply like this. Thank you very much. :)
Ed Nutting at 5-Mar-12 12:27pm
   
Glad I could help, though I think you mean the word "dumb" not "dump" - a minor mix-up ;P
iKrshnan at 6-Mar-12 11:25am
   
yh.. a minor mistake.. :) :P

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)

  Print Answers RSS
0 Dnyaneshwar@Pune 1,300
1 Sergey Alexandrovich Kryukov 642
2 Tadit Dash 350
3 ravikhoda 300
4 Manas Bhardwaj 240
0 Sergey Alexandrovich Kryukov 11,271
1 OriginalGriff 6,865
2 Peter Leow 4,795
3 Abhinav S 3,838
4 Maciej Los 3,575


Advertise | Privacy | Mobile
Web04 | 2.8.140421.2 | Last Updated 4 Mar 2012
Copyright © CodeProject, 1999-2014
All Rights Reserved. Terms of Use
Layout: fixed | fluid