Srikanth Technologies

Server in Java, Client in C# and Data in XML

In this blog we will see how to send data in XML from a Server Socket in Java to a Client Socket in C#.

The following are different components used in this blog :

Server Application in Java

Java application creates a server socket to receive name from client and send contact details in the form of XML. The following is the code to create Server Socket.

First lets create a class to represent a contact as follows:

public class Contact {
    private String name, mobile, email;
    public Contact(String name, String mobile, String email) {
        this.name = name;
        this.mobile = mobile;
        this.email = email;
    }
    public Contact() {
    }
    public String getName() {
        return name;
    }
    public void setName(String name) {
        this.name = name;
    }
    public String getMobile() {
        return mobile;
    }
    public void setMobile(String mobile) {
        this.mobile = mobile;
    }
    public String getEmail() {
        return email;
    }
    public void setEmail(String email) {
        this.email = email;
    }
}

New lets create ContactsServer, which creates Server Socket and sends contact details for the given name.

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

public class ContactsServer {
    public static void main(String[] args) throws Exception {
        ArrayList<Contact> contacts = new ArrayList<>();
        contacts.add(new Contact("Steve", "9090909090", "steve@gmail.com"));
        contacts.add(new Contact("Bill", "9988776655", "bill@hotmail.com"));
        contacts.add(new Contact("Jack", "9876543210", "jack@yaho.com"));
        contacts.add(new Contact("Larry", "8877996655", "larry@gmail.com"));
        
        ServerSocket serversocket = new ServerSocket(1133, 10);
        System.out.println("Contacts server is ready ....");

        while (true) {
            Socket client = serversocket.accept();
            // take input and output streams
            Scanner scanner = new Scanner(client.getInputStream());
            PrintWriter pw = new PrintWriter(client.getOutputStream(), true);
            // find contact with the given name
            String name = scanner.nextLine();
            boolean found = false;
            for (Contact c : contacts) {
                if (c.getName().equals(name)) {
                    found = true;
                    // convert contact to XML
                    String xml = "<contact><mobile>" + c.getMobile() + "</mobile><email>" + c.getEmail() + "</email></contact>";
                    pw.println(xml);
                }
            }
            if (!found) {
                pw.println("<error>Name not found</error>");
            }
            client.close();
        }
    }
}

Run Server (Server.java) to create a server socket that listens on port number 1133

Client Application in C#

Client application takes name from user, sends it to server and reads Contact details sent from server in the form of XML. If name is not found then server sends XML document with <error> element containing the error message, otherwise it sends details in <contact> element.

Client application is a Console Applicatin in C#. Here is the code for client application.

class ContactClient
    {
        static void Main(string[] args)
        {
            // connect to server
            TcpClient client =  new TcpClient("localhost", 1133);

            Console.Write("Enter name : ");
            String name = Console.ReadLine(); 

            // send name to server
            byte[] buf;
            // append newline as server expects a line to be read
            buf = Encoding.UTF8.GetBytes(name + "\n"); 

            NetworkStream stream = client.GetStream();
            stream.Write(buf, 0, name.Length + 1);

            // read xml from server

            buf = new byte[100];
            stream.Read(buf, 0, 100);
            string xml = Encoding.UTF8.GetString(buf);
            // take only upto first null char
            xml = xml.Substring(0, xml.IndexOf( char.ConvertFromUtf32(0))); 

            XmlDocument doc = new XmlDocument();
            doc.LoadXml(xml);

            if (doc.DocumentElement.Name == "error")
                Console.WriteLine("Name not found!");
            else
            {
                Console.WriteLine("Mobile : {0}", doc.SelectSingleNode("//mobile").InnerText);
                Console.WriteLine("Email  : {0}", doc.SelectSingleNode("//email").InnerText);
            }
        }
    }

Run client application from Visual Studio while server is running. When prompted enter Bill as name and you will get details of contact as shown below :