Write a java program using TCP that enables chatting between client and server.

 Here we create two classes ServerChat and ClientChat that utilize ServerSocket and Socket classes. Sockets use the TCP/IP protocol by default. Below is the code that performs the actual chatting:


//ServerChat.java

import java.io.*;

import java.net.*;

import java.util.Scanner;

public class ServerChat {

public static void main(String[] args) throws IOException {

//create a server socket

ServerSocket serverSocket = new ServerSocket(8000);

//listen for client request

Socket socket = serverSocket.accept();

//create data input and output streams

DataInputStream inputFromClient = new

DataInputStream(socket.getInputStream());

DataOutputStream outputToClient = new

DataOutputStream(socket.getOutputStream());

Scanner sc = new Scanner(System.in);

String msg;

while (true) {

msg = inputFromClient.readUTF();

System.out.println("Client says:" + msg);

System.out.println("(From Server) Input message to client:");

msg = sc.nextLine();

outputToClient.writeUTF(msg);

}

}

}


//ClientChat.java

import java.io.*;

import java.net.Socket;

import java.util.Scanner;

public class ClientChat {

public static void main(String[] args) throws IOException {

//create a socket to connect to the server

Socket socket = new Socket("localhost", 8000);


//create an input stream to retrieve data from the server

DataInputStream fromServer = new DataInputStream(socket.getInputStream());


//create an output stream to send data to the server

DataOutputStream toServer = new

DataOutputStream(socket.getOutputStream());

Scanner sc = new Scanner(System.in);

String msg;

while (true) {

System.out.println("(From Client)Input message to server:");

msg = sc.nextLine();

toServer.writeUTF(msg);

msg = fromServer.readUTF();

System.out.println("Server:" + msg);

}

}

}

Comments

Popular posts from this blog

Short note on E-Government Architecture

Discuss classification or taxonomy of virtualization at different levels.

Explain cloud computing reference model .