Click here to Skip to main content
15,867,568 members
Please Sign up or sign in to vote.
2.00/5 (1 vote)
I need to create client server application in which server listens on one port and sends response on another port for same client. I have created something like this which is not working and i guess i am not even near to send and receive on different port. Though i have achieved this for same port. Help highly Appreciated. Thanks

Server:-
C#
public void createListener()
{

    TcpListener tcpListener = null;
    IPAddress ipAddress = IPAddress.Any;
    try
    {
        tcpListener = new TcpListener(ipAddress, 1818);
        tcpListener.Start();
        output = "Waiting for a connection...";
    }
    catch (Exception e)
    {
        output = "Error: " + e.ToString();
        MessageBox.Show(output);
    }
    while (true)
    {             
        Thread.Sleep(10);            
        TcpClient tcpClient = tcpListener.AcceptTcpClient();
        byte[] bytes = new byte[256];
        NetworkStream stream = tcpClient.GetStream();
        stream.Read(bytes, 0, bytes.Length);
        SocketHelper helper = new SocketHelper();
        helper.processMsg(tcpClient, stream, bytes);                
    }
}

class SocketHelper
{
    TcpClient mscClient;
    string mstrMessage;
    string mstrResponse;
    byte[] bytesSent;
   
    public void processMsg(TcpClient client, NetworkStream stream, byte[] bytesReceived)
    {
        mstrMessage = Encoding.ASCII.GetString(bytesReceived, 0, bytesReceived.Length);
        mscClient = client;
        if (mstrMessage.Length>0)
        {
            mstrResponse = mstrMessage;
        }
        else
        {
            mstrResponse = "You have sent blank message";
        }
        bytesSent = Encoding.ASCII.GetBytes(mstrResponse);
        stream.Write(bytesSent, 0, bytesSent.Length);
    }
   
}
      
private void button1_Click(object sender, EventArgs e)
{
    button1.Text = "Now Listening";
    this.createListener();
}

Client:--
C#
static string output = "";
public Client()
{
    InitializeComponent();
}
public void createListener()
{

    TcpListener tcpListener = null;

    IPAddress ipAddress = IPAddress.Any;
    try
    {

        tcpListener = new TcpListener(ipAddress, 1819);
        tcpListener.Start();
        output = "Waiting for a connection...";
    }
    catch (Exception e)
    {
        output = "Error: " + e.ToString();
        MessageBox.Show(output);
    }
    while (true)
    {
        Thread.Sleep(10);
        TcpClient tcpClient = tcpListener.AcceptTcpClient();
        byte[] bytes = new byte[256];
        NetworkStream stream = tcpClient.GetStream();                
        stream.Read(bytes, 0, bytes.Length);
        string output = "";
    }
}
static string Connect(string serverIP, string message)
{
    string output = "";

    try
    {

        Int32 port = 1818;
        TcpClient client = new TcpClient(serverIP, port);

        Byte[] data = new Byte[256];
        data = System.Text.Encoding.ASCII.GetBytes(message);

        NetworkStream stream = client.GetStream();


        stream.Write(data, 0, data.Length);

        output = "Sent: " + message;
        MessageBox.Show(output);
 
        data = new Byte[256];
 
        String responseData = String.Empty;
 
        Int32 bytes = stream.Read(data, 0, data.Length);
        responseData = System.Text.Encoding.ASCII.GetString(data, 0, bytes);
        output = "Received: " + responseData;
        MessageBox.Show(output);
 
        stream.Close();
        client.Close();
        return responseData;
    }
    catch (ArgumentNullException e)
    {
        output = "ArgumentNullException: " + e;
        MessageBox.Show(output);
        return e.Message;
    }
    catch (SocketException e)
    {
        output = "SocketException: " + e.ToString();
        MessageBox.Show(output);
        return e.Message;
    }
}

private void button1_Click(object sender, EventArgs e)
{
    string serverIP = "192.168.0.205";
    string message = textBox1.Text;
    textBox2.Text=Connect(serverIP, message);
}
Posted
v3
Comments
Sergey Alexandrovich Kryukov 10-Sep-13 11:02am    
Not clear. I did not look through your all code, but when a response is sent using TCP, the listening part accepts the connection and obtains the instance of TcpClient and sends response to it. TcpClient does not have any IO address or port, it uses the channel created as a result of connection.
—SA
eyecondeveloper 11-Sep-13 0:51am    
ok let me explain i need to create a client server application in which client uses port 1818 to send request let say "Hello" to server and server listens on same port then server should reply back using port 1819 let say "Good Morning" and client should listen that reply with 1819 port and print that received message in label or something
.. hope this will explain
Sergey Alexandrovich Kryukov 11-Sep-13 1:20am    
No, this is not how TCP session works. Of course, a client can also listen, but why? You are not asking for server push. Anyway, the client should give the server IP address and port and play the role of server (listen on this port). From what you say, there is no a need in it.
—SA
eyecondeveloper 11-Sep-13 1:31am    
ok again let me explain in brief there are no. of clients and one server..
i need to create client server app in which if on client changes anything then it will reflect on each and every client which is attached to server. server will work like dispatcher. i need to insert record in DB if record inserted successfully then show that record on each client without retrieving from DB... server should broadcast that record on each client attached with it. i did this in web application through Caching but how to do it in Desktop application.. and different ports should be used to prevent data collision and traffic.
Sergey Alexandrovich Kryukov 11-Sep-13 1:42am    
The answer is the same. The server should keep all instances of TcpClient in some collection and send information to them as soon as they are connected. No listening by clients is ever needed. Look, finally, concentrate and try to understand it.
—SA

Please see my comments to the question. You can find some useful ideas in my past answers:
Multple clients from same port Number[^],
an amateur question in socket programming[^].

What you describe looks similar to publisher-subscriber model. You can treat TCP connection as subscription. This way, you won't need clients to listen. And even if you needed that, you would not need a separate port (it just doesn't matter).

—SA
 
Share this answer
 
Comments
eyecondeveloper 11-Sep-13 2:08am    
Sergey Alexandrovich thanks for speedy reply's, mate really appreciate it.
I am trying it now will let u know if any query. thanks
Sergey Alexandrovich Kryukov 11-Sep-13 2:45am    
Sure.
—SA
eyecondeveloper 11-Sep-13 3:03am    
i need sample code can u please help me out?
Sergey Alexandrovich Kryukov 11-Sep-13 3:30am    
Well, it hardly can be a small fragment of code, rather a topic for an article...
Maybe you can just ask what's unclear?..
—SA
eyecondeveloper 11-Sep-13 4:20am    
ok go through my above code and tell me where do i need to change i get ur idea of storing all instance in collection. its good one but apart from that where do i need to change.
this following article helped for this.
A Chat Application Using Asynchronous UDP sockets[^]

good job hitesh
 
Share this answer
 

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



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900