Wednesday 22 August 2018

Client in C# and Server in Java

In my previous posts, I explained simple client, server communication. In this post, I am going to explain an application, where client is implemented in C# and server is implemented in Java.

CustomServer.java : Receive data from client and convert it to upper case.

Client.cs : Send data to client and receive response from client.

CustomServer.java
/**
 * Accept connections from client sockets and convert the string to uppercase.
 * 
 * @author Hari krishna
 */

import java.io.IOException;
import java.io.PrintWriter;
import java.net.ServerSocket;
import java.net.Socket;
import java.util.Scanner;

public class CustomServer {

 private int port;
 private int backlog;

 public CustomServer(int port, int backlog) {
  this.port = port;
  this.backlog = backlog;
 }

 public void startServer() {
  try (ServerSocket serverSocket = new ServerSocket(port, backlog)) {

   System.out.println("Started Listening for clients");
   while (true) {

    // take input and output streams
    try (Socket client = serverSocket.accept();
      Scanner scanner = new Scanner(client.getInputStream());
      PrintWriter pw = new PrintWriter(client.getOutputStream(), true)) {
     String dataFromClient = scanner.nextLine();

     String response = getResponse(dataFromClient);
     pw.write(response);

    }catch(Exception e){
     e.printStackTrace();
    }

   }
  } catch (IOException e) {
   // TODO Auto-generated catch block
   e.printStackTrace();
  }
 }

 private String getResponse(String dataFromClient) {
  return dataFromClient.toUpperCase();
 }

}

Client.cs

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Net;
using System.Net.Sockets;

namespace Sockets
{
    class ClientSocket
    {
        private int port;
        private TcpClient client;
        private NetworkStream stream;

        public ClientSocket(int port, int sendTimeout, int receiveTimeout)
        {
            this.port = port;
            client = new TcpClient("localhost", port);

            client.ReceiveTimeout = sendTimeout;
            client.SendTimeout = receiveTimeout;
            stream = client.GetStream();
        }

        public void processData(String data)
        {
            byte[] buf;

            /* append newline as server expects a line to be read */
            buf = Encoding.UTF8.GetBytes(data+"\n");

            Console.WriteLine("Sending data \'{0}\' to server", data);
            
            stream.Write(buf, 0, data.Length + 1);

            buf = new byte[100];
            int bytesRead = stream.Read(buf, 0, 100);

            byte[] finalData = new byte[bytesRead];

            for(int i=0; i < bytesRead; i++)
            {
                finalData[i] = buf[i];
            }

            string response = Encoding.UTF8.GetString(finalData);

            response = response.TrimEnd();

            Console.WriteLine("Received Response : \'{0}\', of length {1}", response, response.Length);

            client.Close();
        }

    }

    class Client
    {
        static void Main(string[] args)
        {
            try
            {
                ClientSocket clientSock = new ClientSocket(1234, 3000, 3000);
                String data = "Hello World";

                clientSock.processData(data);

            
            }catch(Exception e)
            {
                Console.WriteLine(e.Message);
            }

            Console.WriteLine("Press Enter to close the connection");

            Console.Read();
        }
    }
}


CustomServerDemo.java

public class CustomServerDemo {

 public static void main(String args[]){
  CustomServer customServer = new CustomServer(1234, 10);
  
  customServer.startServer();
  
 }
}

Run CustomServerDemo.java

Run Client.cs, you can able to see following output in console.

Sending data 'Hello World' to server
Received Response : 'HELLO WORLD', of length 11


Previous                                                 Next                                                 Home

No comments:

Post a Comment