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