I have a client and a server. When client connects to server the server sends a message to the client.
If the user clicks on button "New message" I want the server to send a new message to the client.
How can I achieve that?
My code (I have removed all try-Catch)
Client:
private void getExpression() {
Socket s = null;
s = new Socket(serverAddress, serverPort);
out = new ObjectOutputStream(s.getOutputStream());
in = new ObjectInputStream(s.getInputStream());
while (true) {
Expression exp = (Expression) in.readObject();
String message = exp.toString();
expressionLabel.setText(message);
}
}
public void newMessage() throws IOException {
//MAKE SERVER SEND NEW MESSAGE
}
#Override
public void actionPerformed(ActionEvent ae) {
if (ae.getSource().equals(newButton)) {
newMessage();
}
}
Handler:
public class Handler extends Thread {
private Socket socket;
private String address;
public Handler (Socket s) {
socket = s;
address = socket.getInetAddress().getHostAddress();
}
#Override
public void run() {
ObjectInputStream in = null;
ObjectOutputStream out = null;
out = new ObjectOutputStream(socket.getOutputStream());
in = new ObjectInputStream(socket.getInputStream());
out.writeObject(new Expression());
out.flush();
}
Server:
private int port;
public TestProgram(int port) {
this.port = port;
go();
}
public void go() {
ServerSocket ss = null;
ss = new ServerSocket(port);
while (true) {
Socket s = ss.accept();
new Handler(s).start();
}
}
What message are you trying to get? A random message or something preset? Are using a Gui?
IF your using a gui and your trying to get a message I'd expect you to do something like
JButton newButton = new JButton("New Message");
newButton.addActionListener(this);
this.add(newButton);
public void newMessage() {
System.out.println(in.readObject().toString);
}
public void actionPerformed(ActionEvent ae) {
if (ae.getSource().equals(newButton)) {
newMessage();
}
}
Your Back End Client Could Look Something Like This
This is a sample so tear it apart and use what you'd like:
// Client.java: The client sends the input to the server and receives
// result back from the server
import java.io.*;
import java.net.*;
import java.util.*;
public class Client
{
// Main method
public static void main(String[] args)
{
// IO streams
DataOutputStream toServer;
DataInputStream fromServer;
try
{
// Create a socket to connect to the server
Socket socket = new Socket("localhost", 8000);
// Create input stream to receive data
// from the server
fromServer = new DataInputStream(socket.getInputStream());
// Create a output stream to send data to the server
toServer = new DataOutputStream(socket.getOutputStream());
Scanner scan= new Scanner (System.in);
// Continuously send radius and receive area
// from the server
while (true)
{
// Read the m/s from the keyboard
System.out.print("Please enter a speed in meters per second: ");
double meters=scan.nextDouble();
// Send the radius to the server
toServer.writeDouble(meters);
toServer.flush();
// Convert string to double
double kilometersPerHour = fromServer.readDouble();
// Print K/h on the console
System.out.println("Area received from the server is "
+ kilometersPerHour);
}
}
catch (IOException ex)
{
System.err.println(ex);
}
}
}
Your Back End Server Should Look Something Like This
/*
* Created by jHeck
*/
// Server.java: The server accepts data from the client, processes it
// and returns the result back to the client
import java.io.DataInputStream;
import java.io.DataOutputStream;
import java.io.IOException;
import java.net.ServerSocket;
import java.net.Socket;
import java.text.DecimalFormat;
public class Server
{
// Main method
public static void main(String[] args)
{
try
{
// Create a server socket
ServerSocket serverSocket = new ServerSocket(8000);
// Start listening for connections on the server socket
Socket socket = serverSocket.accept();
// Create data input and output streams
DataInputStream inputFromClient = new DataInputStream(socket.getInputStream());
DataOutputStream outputToClient = new DataOutputStream(socket.getOutputStream());
// Continuously read from the client and process it,
// and send result back to the client
while (true)
{
// Convert string to double
double meters = inputFromClient.readDouble();
// Display radius on console
System.out.println("Meters received from client: "
+ meters);
// Compute area
double conversionToKilometers = (meters/1000)*3600;
// Send the result to the client
outputToClient.writeDouble(conversionToKilometers);
//Create double formater
DecimalFormat format = new DecimalFormat("0.00");
String formatedCTK = format.format(conversionToKilometers);
// Print the result to the console
System.out.println("Kilometers per hour = "+ formatedCTK);
}
}
catch(IOException ex)
{
System.err.println(ex);
}
}
}
Related
Now I'm done with the application which have the server and client, server accepts the client request and add the client object into the Arraylist and starts a new thread for each clients. when multiple clients connects, clients can list all the clients, and they can send a message to any clients in the list. For example client1, client2, client3 connects to the server client1 and client2 sending a message to the client3,It will be printed in client3 console. all working fine. Now i need to add additional feature that each clients sends a message in individual chat, if client1 opens a chat with client2 the conversation between those two clients only should be displayed, not client3 messages, and vice versa. To do that implementation do i need any additional concept like multi threading. I'm not asking a source code, I'm just asking a idea to implement the above feature.
Can anyone tell me the suggestion or reference to implement separate chats for different clients... Need to keep the old messages until the server goes offline?
Server.java
package server;
import java.io.DataInputStream;
import java.io.IOException;
import java.net.*;
import java.util.Vector;
public class Server {
static Vector<ClientHandler> AllClients = new Vector<ClientHandler>();
public static void main(String args[]) throws Exception {
try {
ServerSocket ss = new ServerSocket(1111);
System.out.println("Server Started");
while(true) {
Socket s = ss.accept();
DataInputStream dis = new DataInputStream(s.getInputStream());
String clientname = dis.readUTF();
System.out.println("Connected With : "+clientname);
ClientHandler client = new ClientHandler(s,clientname);
Thread t = new Thread(client);
AllClients.add(client);
t.start();
System.out.println("Ready to accept connections...");
}
} catch (IOException e) {
e.printStackTrace();
}
}
}
ClientHandler.java
package server;
import java.io.DataInputStream;
import java.io.DataOutputStream;
import java.net.Socket;
import java.util.Scanner;
public class ClientHandler extends Thread{
private DataInputStream in;
private DataOutputStream out;
private String ClientName;
private boolean login;
private Socket Socket;
Scanner sc = new Scanner(System.in);
ClientHandler(Socket s,String name) throws Exception{
this.in = new DataInputStream(s.getInputStream());
this.out = new DataOutputStream(s.getOutputStream());
this.login = true;
this.ClientName = name;
this.Socket = s;
}
public void run() {
while(true) {
try {
String received = in.readUTF();
if(received.equalsIgnoreCase("logout")) {
this.login = false;
this.out.writeUTF("logout");
int i;
for(i = 0; i < Server.AllClients.size(); i++) {
if(this.ClientName.equals(Server.AllClients.get(i).ClientName))
break;
}
Server.AllClients.remove(i);
System.out.println(this.ClientName+" logged out");
this.Socket.close();
break;
}
if(received.equalsIgnoreCase("getlist")) {
for(int i = 0; i < Server.AllClients.size(); i++) {
out.writeUTF(i+1 +", "+Server.AllClients.get(i).ClientName);
}
continue;
}
if(received.contains(",")) {
String[] Message = received.split(",");
for(ClientHandler c : Server.AllClients) {
if(c.ClientName.equalsIgnoreCase(Message[1]) && c.login) {
c.out.writeUTF(this.ClientName +" : "+ Message[0]);
c.out.flush();
break;
}
}
}
}catch(Exception e) {
System.out.println("Error :"+e.getMessage());
}
}
try {
this.in.close();
this.out.close();
}catch(Exception e) {
System.out.println(e.getMessage());
}
}
}
Client.java
package client;
import java.io.*;
import java.net.*;
import java.util.Scanner;
public class Client {
static DataInputStream dis;
static DataOutputStream dos;
static Socket s;
public static void main(String args[])throws Exception {
Scanner sc = new Scanner(System.in);
System.out.println("Enter Cient Name : ");
String name = sc.nextLine();
s = new Socket("localhost",1111);
dis = new DataInputStream(s.getInputStream());
dos = new DataOutputStream(s.getOutputStream());
dos.writeUTF(name);
Thread sendMessage = new Thread(new Runnable()
{
#Override
public void run() {
while (true) {
String msg = sc.nextLine();
try {
dos.writeUTF(msg);
if(msg.equalsIgnoreCase("logout")) {
System.out.println("Logged out");
break;
}
} catch (IOException e) {
System.out.println("Error in send method :"+e.toString());
}
}
}
});
Thread readMessage = new Thread(new Runnable()
{
#Override
public void run() {
while (true) {
try {
String msg = dis.readUTF();
if(msg.equalsIgnoreCase("logout")) {
System.out.println("Logged out");
break;
}
System.out.println(msg);
} catch (IOException e) {
System.out.println("Error in read method :"+e.getMessage());
}
}
}
});
sendMessage.start();
readMessage.start();
}
}
If my code have any irrelevant statements please do suggest a better way to optimise the code
The first answer is: yes it is possible.
The second answer: it's not about threading, you have to think in the first place (it's important, but not in the frist place).
the third answer: as i understand your code, the main data-structre is the collection of clients and their handler. In my opinion there is a further abstraction-layer missing in between.
In the frist place think about a data structure like "chatRoom". A client connecting to server has to send a "chatRoom"-name to the the server. Than the server creates the chatRoom or adds the client to the chatRooom's client-set. From that point a client can send his messages to the chatRoom not to the client directly anymore.
In a further step: To enable sending messages to inidividual clients you can e.g. enforce a chatRoom for every pair of clients (take care: this can be very expansive), so individual communication between clients is still possible.
my server class
import java.net.*;
import java.io.*;
public class server
{
private Socket socket;
private ServerSocket server;
// constructor with port
public void start(int port){
try {
server = new ServerSocket(port);
while(true){
socket = server.accept();
new ConnectionHandler(socket).run();
}
}catch(IOException i){
}
}
}
class ConnectionHandler implements Runnable{
private Socket socket = null;
private ServerSocket server = null;
private DataInputStream in = null;
public ConnectionHandler(Socket socket){
this.socket=socket;
}
#Override
public void run() {
InputStream inp = null;
BufferedReader brinp = null;
DataOutputStream out = null;
try
{
System.out.println("Waiting for a client ...");
System.out.println(server);
System.out.println("Client accepted");
in = new DataInputStream(new BufferedInputStream(socket.getInputStream()));
String line = "";
// reads message from client until "Over" is sent
while (!line.equals("Over"))
{
try
{
line = in.readUTF();
System.out.println(line);
}
catch(IOException i)
{
System.out.println(i);
}
}
System.out.println("Closing connection");
// close connection
socket.close();
in.close();
}
catch(IOException i)
{
System.out.println(i);
}
}
public static void main(String[] args) {
server serverr = new server();
serverr.start(4000);
}
}
Here's my client class.
import java.net.*;
import java.io.*;
public class Client
{
// initialize socket and input output streams
private Socket socket = null;
private DataInputStream input = null;
private DataOutputStream out = null;
// constructor to put ip address and port
public Client(String address, int port)
{
// establish a connection
try
{
socket = new Socket(address, port);
System.out.println("Connected");
// takes input from terminal
input = new DataInputStream(System.in);
// sends output to the socket
out = new DataOutputStream(socket.getOutputStream());
}
catch(UnknownHostException u)
{
System.out.println(u);
}
catch(IOException i)
{
System.out.println(i);
}
// string to read message from input
String line = "";
// keep reading until "Over" is input
while (!line.equals("Over"))
{
try
{
line = input.readLine();
out.writeUTF(line);
}
catch(IOException i)
{
System.out.println(i);
}
}
// close the connection
try
{
input.close();
out.close();
socket.close();
}
catch(IOException i)
{
System.out.println(i);
}
}
public static void main(String args[])
{
Client client = new Client("127.0.0.1", 4000);
}
}
Trying to develop pretty simple chat application works via terminal, but I think there are plenty of bugs I have in my code.
The server can handle one client, but when another client comes up it doesn't connect to other clients.
What am I have to do now?
I couldn't find out where my problem is, waiting your helps.
Note: I am completely new to socket programming concept.
The ConnectionHandler class is a thread class, and you must wrap its object to a Thread instance and then call start() instead of run().
So in the Server class change
new ConnectionHandler(socket).run();
with
new Thread(ConnectionHandler(socket)).start();
I recently wrote a socket communication program in java where two threads run concurrent on each server and client side handling the read and write operations to the socket allowing continuous message sending and receiving on both sides.
The problem is either of the client or the server stops receiving communication from the other side and then after a while both of them stop working. I can't figure out what's wrong and how the connection is dropping :/
Code for server
import java.net.*;
import java.io.*;
import java.util.Scanner;
public class Server
{
private Socket socket = null;
private ServerSocket server = null;
private DataInputStream in = null;
private DataOutputStream out = null;
private Scanner inp = null;
String line = "";
String iline = "";
public Server(int port)
{
try
{
server = new ServerSocket(port);
System.out.println("Server started");
System.out.println("Waiting for a client ...");
socket = server.accept();
System.out.println("Client accepted");
// takes input from the client socket
out=new DataOutputStream(socket.getOutputStream());
in = new DataInputStream(new
BufferedInputStream(socket.getInputStream()));
inp = new Scanner(System.in);
while (true)
{
new Thread(new Runnable(){
public void run()
{
try{
while(true){
line = in.readUTF();
System.out.println("Client : "+line);
if(socket.isClosed()||socket.isOutputShutdown()||socket.isInputShutdown())
{
System.out.println("DED");
System.exit(0);
}
}
}
catch(Exception e){
System.out.println("Exception !!!");
}
}
}).start();
iline=inp.nextLine();
out.writeUTF(iline);
if(socket.isClosed()||socket.isOutputShutdown()||socket.isInputShutdown()){
System.out.println("DED");
System.exit(0);
}
}
}
catch(IOException i)
{
System.out.println(i);
}
}
public static void main(String args[])
{
Server server = new Server(5000);
}
}
Code for Client
import java.net.*;
import java.io.*;
import java.util.Scanner;
class Client{
private Socket socket =null;
private DataInputStream inp=null;
private DataOutputStream out=null;
private Scanner in=null;
String line="";
String iline="";
Client(String address,int port)
{
try{
socket = new Socket(address,port);
in= new Scanner(System.in);
out = new DataOutputStream(socket.getOutputStream());
inp = new DataInputStream(new BufferedInputStream(socket.getInputStream()));
while(true){
line=in.nextLine();
out.writeUTF(line);
new Thread(new Runnable(){
public void run()
{
try{
while(true){
iline=inp.readUTF();
System.out.println("Server : "+iline);
if(socket.isClosed()||socket.isOutputShutdown()||socket.isInputShutdown()){
System.out.println("DED");
System.exit(0);
}
}
}
catch(Exception e){
System.out.println("Exception !!!");
}
}
}).start();
if(socket.isClosed()||socket.isOutputShutdown()||socket.isInputShutdown()){
System.out.println("DED");
System.exit(0);
}
}
}
catch(UnknownHostException u)
{
System.out.println(u);
}
catch(Exception e){
System.out.println("EXCEPTION!!!");
}
}
}
class ClientSocket{
public static void main(String...args){
Client obj = new Client("127.0.0.1", 5000);
}
}
Just an initial run through your code what I see is in the first while(true){} , you are spawning a thread calling start method on it . The moment you start the reading thread the main thread checks fo sockets conditions and moves ahead. Since there is a true in your first while(true) a new thread is again spawned and that goes on an on until the socket is closed where the programs terminates because of system.exit call.
This question already has answers here:
How do I compare strings in Java?
(23 answers)
Closed 4 years ago.
I wrote a java application for both Server and Client. What I want to do is stop the Client's application(and all of it's threads) when the user enters the word: "logout". I've tried everything I could find so kinda desperate here. Please send help!
Here is my code for Client.java
package client;
//Java implementation for multithreaded chat client
//Save file as Client.java
import java.io.*;
import java.net.*;
import java.util.Scanner;
public class Client extends Thread
{
final static int ServerPort = 1234;
private volatile static boolean running = true;
public static void main(String args[]) throws UnknownHostException, IOException
{
Scanner scn = new Scanner(System.in);
// getting localhost ip
InetAddress ip = InetAddress.getByName("localhost");
// establish the connection
Socket s = new Socket(ip, ServerPort);
// obtaining input and out streams
DataInputStream dis = new DataInputStream(s.getInputStream());
DataOutputStream dos = new DataOutputStream(s.getOutputStream());
// sendMessage thread
Thread sendMessage = new Thread(new Runnable()
{
#Override
public void run() {
while (running) {
// read the message to deliver.
try {
String msg = scn.nextLine();
if(msg == "logout") {
running = false;
dis.close();
dos.close();
scn.close();
s.close();
Thread.currentThread().interrupt();
break;
}
dos.writeUTF(msg);
}
catch (IOException e) {
if(!running) {
System.out.println("Closing...");
System.exit(0);
}
}
} }
});
// readMessage thread
Thread readMessage = new Thread(new Runnable()
{
#Override
public void run() {
while (running) {
// read the message sent to this client
try {
String msg = dis.readUTF();
if(sendMessage.isInterrupted()) {
running = false;
dis.close();
dos.close();
scn.close();
s.close();
Thread.currentThread().interrupt();
break;
}
System.out.println(msg);
} catch (IOException e) {
if(!running) {
System.out.println("Closing...");
System.exit(0);
}
}
}
}
});
sendMessage.start();
readMessage.start();
}
}
And this is my Server.java
package server;
//Java implementation of Server side
//It contains two classes : Server and ClientHandler
//Save file as Server.java
import java.io.*;
import java.util.*;
import java.net.*;
//Server class
public class Server
{
// Vector to store active clients
static Vector<ClientHandler> ar = new Vector<>();
// counter for clients
static int i = 0;
public static void main(String[] args) throws IOException
{
// server is listening on port 1234
ServerSocket ss = new ServerSocket(1234);
Socket s;
// running infinite loop for getting
// client request
while (true)
{
// Accept the incoming request
s = ss.accept();
System.out.println("New client request received : " + s);
// obtain input and output streams
DataInputStream dis = new DataInputStream(s.getInputStream());
DataOutputStream dos = new DataOutputStream(s.getOutputStream());
System.out.println("Creating a new handler for this client...");
// Create a new handler object for handling this request.
ClientHandler mtch = new ClientHandler(s,"client " + i, dis, dos);
// Create a new Thread with this object.
Thread t = new Thread(mtch);
System.out.println("Adding this client to active client list");
// add this client to active clients list
ar.add(mtch);
// start the thread.
t.start();
// increment i for new client.
// i is used for naming only, and can be replaced
// by any naming scheme
i++;
}
}
}
//ClientHandler class
class ClientHandler implements Runnable
{
private String name;
final DataInputStream dis;
final DataOutputStream dos;
Socket s;
boolean isloggedin;
// constructor
public ClientHandler(Socket s, String name,
DataInputStream dis, DataOutputStream dos) {
this.dis = dis;
this.dos = dos;
this.name = name;
this.s = s;
this.isloggedin=true;
}
#Override
public void run() {
String received;
while (true)
{
try
{
// receive the string
received = dis.readUTF();
if(received.equals("logout")){
break;
}
// break the string into message and recipient part
StringTokenizer st = new StringTokenizer(received, "#");
String MsgToSend = st.nextToken();
String recipient = st.nextToken();
// search for the recipient in the connected devices list.
// ar is the vector storing client of active users
for (ClientHandler mc : Server.ar)
{
// if the recipient is found, write on its
// output stream
if (mc.name.equals(recipient) && mc.isloggedin==true)
{
mc.dos.writeUTF(this.name+" : "+MsgToSend);
break;
}
}
} catch (IOException e) {
e.printStackTrace();
}
}
try
{
// closing resources
this.dis.close();
this.dos.close();
this.s.close();
this.isloggedin=false;
}catch(IOException e){
e.printStackTrace();
}
}
}
Code reference: Multithread GroupChat 1
Multithread GroupChat 2
Don't compare Strings with == but with equals(). msg == "logout" Should be msg.equals("logout").
Can someone look at my code and tell me what's wrong?
I am trying to make a client server chat program and want server to accept endless connections requested from the clients. It runs successfully. At First run, server and client are able to chitchat properly but when the client is closed(quit) and again came back, client is able to connect with
server and even it can send messages to server and messages are also received by the server BUT there is issue at server side, At Server side server messages are not reach to client properly. Some messages are skipped and are not able to reached to client immediately as it was before in the first run.Please help me if anyone can find this solution.
SERVER CODE:
//packages
import java.io.*;
import java.net.*;
import java.lang.*;
public class Server1 {
public static void main(String[] args) throws IOException {
// Instance variable fields
ServerSocket listener=null;
Socket clientSocket=null;
final int port = 444;
System.out.println("Server waiting for connection on port "+port);
try
{
listener = new ServerSocket(port);
// Creates a server socket bound to the specified port.
}
catch(IOException e)
{
e.printStackTrace();
}
while(true)
{
try
{
clientSocket = listener.accept(); //Listens for a connection to be made to this socket and accepts it.
//clientsocket is now the route through which we can communicate with the client.
//if we reach here, the server got a call already...
System.out.println("You have succesfully connected");
/*Returns local address of this serversocket and
Returns the remote port number to which this socket is connected. */
System.out.println("Recieved connection from "+clientSocket.getInetAddress() +" on port "+clientSocket.getPort());
new echoThread(clientSocket).start(); //new thread for a client
}
catch( IOException e)
{
System.out.println("I/O error "+e);;
}
}
}
}
class echoThread extends Thread{
Socket clientSocket; // instance variable field
//For every client we need to start separate thread.
public echoThread(Socket clientSocket) //constructor
{
this. clientSocket = clientSocket;
}
//create two threads to send and recieve from client
public void run()
{
RecieveFrmClientThread recieve = new RecieveFrmClientThread(this.clientSocket);
Thread thread = new Thread(recieve);
thread.start();
SndToClientThread send = new SndToClientThread(this.clientSocket);
Thread thread2 = new Thread(send);
thread2.start();
}
}
//INCOMING
class RecieveFrmClientThread implements Runnable
{
Socket clientSocket=null;
BufferedReader br = null;
public RecieveFrmClientThread(Socket clientSocket)
{
this.clientSocket = clientSocket;
} //end constructor
public void run() {
try{
br = new BufferedReader(new InputStreamReader(this.clientSocket.getInputStream()));
//returns the input stream through which the server can hear the client.
String messageString="";
System.out.println("Please enter something to send back to client..");
while(true){
while((messageString = br.readLine())!= null)
{//assign message from client to messageString
if(messageString.equals("EXIT"))
{
System.out.println("you have been logout from it");
//break;//break to close socket if EXIT
}
System.out.println("From Client: " + messageString);//print the message from client
messageString="";
}
}
}
catch(Exception ex){System.out.println(ex.getMessage());}
}
}//end class RecieveFromClientThread
//OUTGOING
class SndToClientThread implements Runnable
{
//instance field variables
PrintWriter pwPrintWriter;
Socket clientSock = null;
public SndToClientThread(Socket clientSock)
{
this.clientSock = clientSock;
}
public void run() {
try{
pwPrintWriter =new PrintWriter(this.clientSock.getOutputStream(),true);//returns the output stream through which the server can talk to the client,
while(true)
{
String msgToClientString = null;
BufferedReader input = new BufferedReader(new InputStreamReader(System.in));//get input from server
msgToClientString = input.readLine();//read message from server to send it to client
if(msgToClientString.equals("EXIT"))
{
System.out.println("Disconnecting Client!!");
//System.exit(0);
}
pwPrintWriter.println(msgToClientString);//send message to client with PrintWriter
pwPrintWriter.flush();//flush the PrintWriter
}//end while
}
catch(Exception ex){System.out.println(ex.getMessage());}
}//end run
}//end class SendToClientThread
CLIENT CODE :
import java.io.*;
import java.net.*;
public class Client1 {
//Instance variable field
//private ServerSocket ss;
public static void main(String[] args)
{
try {
Socket sock = new Socket("localhost",444);
/*//create two threads to send and recieve from client
RecieveFromServer recieveThread = new RecieveFromServer(sock);
System.out.println("SOCK=" +sock);
Thread thread2 =new Thread(recieveThread);
thread2.start();
SendToServer sendThread = new SendToServer(sock);
Thread thread = new Thread(sendThread);
thread.start();*/
new echoThread1(sock).start(); //new thread for a client
}
catch (Exception e) {System.out.println(e.getMessage());}
}
}
class echoThread1 extends Thread {
Socket sock;
public echoThread1(Socket sock) {
this.sock = sock;
}
//create two threads to send and recieve from client
public void run()
{
RecieveFromServer recieveThread = new RecieveFromServer(this.sock);
Thread thread = new Thread(recieveThread);
thread.start();
SendToServer sendThread = new SendToServer(this.sock);
Thread thread2 = new Thread(sendThread);
thread2.start();
}
}
class RecieveFromServer implements Runnable
{
Socket sock=null;
BufferedReader recieve=null;
public RecieveFromServer(Socket sock) {
this.sock = sock;
}//end constructor
public void run() {
try{
recieve = new BufferedReader(new InputStreamReader(sock.getInputStream()));//get inputstream for this socket
String msgRecieved = null;
while((msgRecieved = recieve.readLine())!= null)
{
System.out.println("From Server: " + msgRecieved);
}
}catch(Exception e){System.out.println(e.getMessage());}
}//end run
}//end class RecieveFromServer
class SendToServer implements Runnable
{
Socket sock=null;
PrintWriter print=null;
BufferedReader brinput=null;
public SendToServer(Socket sock)
{
this.sock = sock;
}//end constructor
public void run(){
try{
if(this.sock.isConnected()) //Returns TRUE if the socket is successfuly connected to a server
{
System.out.println("Client connected to "+this.sock.getInetAddress() + " on port "+this.sock.getPort());
this.print = new PrintWriter(sock.getOutputStream(), true);
System.out.println("Type your message to send to server..type 'EXIT' to exit");
while(true){
brinput = new BufferedReader(new InputStreamReader(System.in)); // input from client
String msgtoServerString=null;
msgtoServerString = brinput.readLine();
this.print.println(msgtoServerString);
this.print.flush();
if(msgtoServerString.equals("EXIT"))
{
System.out.println("you have logged out of server...Thanks for your visit");
sock.close();
break;}
}
}//end while
}
catch(Exception e){System.out.println(e.getMessage());}
}//end run method
}//end class SendToServer