I am running a client on android emulator and server (java) on the same PC and am using socket programming. Attaching code below. Individually both are running fine but the actual data transfer is not happening and am not able to figure it out.
Server side(PC):
import java.net.*;
import java.io.*;
public class Server_tcp {
void run(){
{
try {
System.out.println("In 1st try blck");
try {
System.out.println("In 2nd try blck");
Boolean end = false;
ServerSocket ss = new ServerSocket(4444);
System.out.println("socket created");
while(!end){
//Server is waiting for client here, if needed
Socket s = ss.accept();
System.out.println("socket accepted");
BufferedReader input = new BufferedReader(new InputStreamReader(s.getInputStream()));
PrintWriter output = new PrintWriter(s.getOutputStream(),true); //Autoflush
String st = input.readLine();
System.out.println("Tcp Example" + "From client: "+st);
output.println("Good bye and thanks for all the fish :)");
s.close();
if (st==null){ end = true; }
}
ss.close();
} catch (UnknownHostException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
} catch (IOException exp) {
// TODO Auto-generated catch block
exp.printStackTrace();
}
}
}
public static void main(String args[])
{
Server_tcp server = new Server_tcp();
while(true){
server.run();
}
}
}
Client Side (Android ):
package com.try3;
import android.app.Activity;
import android.os.Bundle;
import android.widget.EditText;
import java.io.*;
import java.net.*;
public class ClientTCPActivity extends Activity {
/** Called when the activity is first created. */
private EditText et;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
System.out.println("Before try net");
trynet();
System.out.println("after try net");
}
public void trynet() {
System.out.println("inside try net");
try {
System.out.println("inside try");
Socket s = new Socket("127.0.0.1",4444);
//outgoing stream redirect to socket
OutputStream out = (OutputStream) et.getContentDescription();
PrintWriter output = new PrintWriter(out);
output.println("Hello Android!");
BufferedReader input = new BufferedReader(new InputStreamReader(s.getInputStream()));
//read line(s)
String st = input.readLine();
System.out.println(st);
//Close connection
s.close();
System.out.println(" try ");
} catch (UnknownHostException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
From the Android Emulator you should be referring to your PC using 10.0.2.2 instead of 127.0.0.1
I didn't understand what you are trying to do here.
OutputStream out = (OutputStream) et.getContentDescription();
PrintWriter output = new PrintWriter(out);
Did you mean something like:
PrintWriter output = new PrintWriter(s.getOutputStream(),true);
??
Related
I am new to Java programming and am trying to develop multi-client chat server.
following is my code:
package Server;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.net.DatagramPacket;
import java.net.DatagramSocket;
import java.net.ServerSocket;
import java.net.Socket;
import java.net.SocketException;
import java.util.ArrayList;
import java.util.List;
public class server implements Runnable{
private List<ServerClient> clients = new ArrayList<ServerClient>();
//private String UID;
private int port;
private ServerSocket socket;
private Thread run, manage, send, receive;
private boolean running = false;
public int i=0;
public server(int port){
// this.UID = UID;
this.port = port;
try {
socket = new ServerSocket(port);
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
run = new Thread(this, "Server");
run.start();
}
#Override
public void run() {
// TODO Auto-generated method stub
running = true;
ManageClients();
receive();
}
private void ManageClients(){
manage = new Thread("Manage"){
public void run(){
while(running){
//managing
}
}
};
manage.start();
}
private void receive(){
receive = new Thread("Receive"){
public void run(){
Socket S1 = null;
try {
S1 = socket.accept();
} catch (IOException e1) {
// TODO Auto-generated catch block
e1.printStackTrace();
}
while(running){
/* byte [] data = new byte[1024];
DatagramPacket packet = new DatagramPacket(data, data.length);
try {
socket.receive(packet);
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
String string = new String(packet.getData());
System.out.println(string);*/
/* BufferedReader br = null;
try {
br = new BufferedReader(new InputStreamReader(S1.getInputStream()));
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
try {
String string = br.readLine();
System.out.println(string);
process(string);
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}*/
process(S1);
System.out.println(String.valueOf(i));
i++;
}
}
};
receive.start();
}
private void process(Socket S1){
BufferedReader br = null;
String string = "";
try {
br = new BufferedReader(new InputStreamReader(S1.getInputStream()));
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
try {
string = br.readLine();
System.out.println(string);
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
if(string.startsWith("/c/")){
clients.add(new ServerClient("name", S1.getInetAddress(), S1.getPort(), "UID"));
}
else if(string.startsWith("/ip/")){
//send ip address to raspberry
System.out.println(string);
}
else if(string.startsWith("/r/")){
//send relay command to relay
System.out.println(string);
}
}
}
The server is accepting only one connection. If I try to connect another user the console does not show any output.
Can you please guide where I am going wrong.
Thank you
You need to run the accept method multiple times... once for each client that wants to connect. Typically people do that on a separate thread in a while loop since the accept method is blocking.
In your code it seems like you are only calling accept once, and hence you will only get one client connection.
I would recommend that you change your code architecture here, but if you want to keep it the same, and you know how many clients will connect, then you could wrap your access to socket in a synchronization lock, and call your receive method once for each client.
I am getting started with java sockets just out of inquisitiveness.
I wrote a small piece of code, a server and a client.
The server accepts a string and converts it to upper case and returns to the client.
I want the server to be able to handle multiple clients and have a persistent connection.
Here is the server code :
package server;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.PrintWriter;
import java.net.ServerSocket;
import java.net.Socket;
import java.net.SocketException;
import java.util.ArrayList;
public class Server {
private ServerSocket listener;
private ArrayList<Socket> clients;
public Server() throws IOException{
clients = new ArrayList<Socket>();
listener = new ServerSocket(7575);
}
public Server(int port) throws IOException{
clients = new ArrayList<Socket>();
listener = new ServerSocket(port);
}
public void start() throws IOException, InterruptedException{
Thread one = new Thread(){
public void run(){
while (true){
Socket socket = null;
try {
socket = listener.accept();
} catch (IOException e1) {
// TODO Auto-generated catch block
e1.printStackTrace();
}
if (socket.isConnected()){
try {
socket.setKeepAlive(true);
} catch (SocketException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
clients.add(socket);
System.out.println(socket.getRemoteSocketAddress().toString());
}
}
}
};
Thread two = new Thread(){
public void run(){
try {
while (true){
work();
}
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
};
one.start();
two.start();
one.join();
two.join();
stop();
}
private void stop() throws IOException{
listener.close();
}
private void work() throws IOException{
if (clients.size() == 0){
return;
}
for(int i = 0; i < clients.size(); i++){
Socket socket = clients.get(i);
if (!socket.isClosed()){
BufferedReader br = new BufferedReader(new InputStreamReader(socket.getInputStream()));
PrintWriter out = new PrintWriter(socket.getOutputStream(), true);
String data = br.readLine();
if (data == null) continue;
out.println(data.toUpperCase());
}
else{
clients.remove(socket);
}
}
}
}
package entry;
import java.io.IOException;
import server.Server;
public class Main {
public static void main(String args[]) throws IOException{
Server server = new Server();
try {
server.start();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
and here is the client :
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.PrintWriter;
import java.net.Socket;
public class Main {
public static void main(String args[])throws IOException{
Socket socket = new Socket("192.168.0.110", 7575);
BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
BufferedReader sr = new BufferedReader(new InputStreamReader(socket.getInputStream()));
PrintWriter pr = new PrintWriter(socket.getOutputStream(), true);
while (true){
System.out.println("\n\nEnter a string : ");
String inp = br.readLine();
if (inp.equals("quit")) break;
pr.println(inp);
System.out.println("The response is : " + sr.readLine());
}
socket.close();
}
}
Strange thing here is when I set a breakpoint in the server code and step through the code in eclipse, the code is working exactly as expected i.e I am getting the response in the client.
But when I run it directly in eclipse, I am not getting the response in the client.
Cannot understand what is going wrong.
Edit
I seem to have fixed the issue.
Here is the code snippet :
Thread two = new Thread(){
public void run(){
try {
while (true){
Thread.sleep(1000); //This is the added line
work();
}
} catch (IOException | InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
};
But I am still confused about what made the timing difference.
Is there any cleaner way to achieve this ?
I've solved the problem with a different approach.
Here is the new Approach:
ServerHandler.java :
package server;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.PrintWriter;
import java.net.Socket;
import java.util.ArrayList;
public class ServerHandler extends Thread{
private Socket socket;
private BufferedReader in;
private PrintWriter out;
private ArrayList<Socket> clients;
public ServerHandler(Socket socket) throws IOException{
this.socket = socket;
clients = new ArrayList<Socket>();
if (!clients.contains(socket)){
clients.add(this.socket);
System.out.println(this.socket.getRemoteSocketAddress());
}
}
#Override
public void run(){
while (true){
if (clients.isEmpty()) break;
String str = null;
for (int i = 0; i < clients.size(); i++){
Socket socket = clients.get(i);
if (socket.isClosed()){
clients.remove(socket);
continue;
}
try {
in = new BufferedReader(new InputStreamReader(socket.getInputStream()));
} catch (IOException e2) {
// TODO Auto-generated catch block
e2.printStackTrace();
}
try {
out = new PrintWriter(socket.getOutputStream(), true);
} catch (IOException e1) {
// TODO Auto-generated catch block
e1.printStackTrace();
}
try {
str = in.readLine();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
out.println(str.toUpperCase());
}
}
}
}
Main.java [for running the server] :
package entry;
import java.io.IOException;
import java.net.ServerSocket;
import server.ServerHandler;
public class Main {
public static void main(String args[]) throws IOException{
ServerSocket listener = new ServerSocket(7575);
try{
while (true){
new ServerHandler(listener.accept()).start();
}
}
catch(Exception e){
e.printStackTrace();
}
finally{
listener.close();
}
}
}
Ok, Here we go.I don't understand the use of Arraylist for maintaining Connections unless You are handling the messy details for each Client.
The most used or prefered approach for handling multiple clients at a time can be understood in terms of an example:
Server.java
import java.net.ServerSocket;
import java.io.IOException;
class Server {
public static void main(String[] args) throws IOException {
try( ServerSocket ss = new ServerSocket(3333)) { // try with resources
new ServerThread(ss.accept()).start();
}
}
}
As you can see, I just defined a Class that will listen for Client connections, and as soon a request is made to the server it will start a Thread which is defined in the next class. A point to be noted here is the use of Try-with-Resources block. Any class that implements the Closeable interface can be enclosed within this try statement. The try-with-resources automatically handles closing of streams or connections for me. This means, you remove all your redundant try-catch blocks from your code and use this try instead.
Now,
ServerThread.java
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.PrintWriter;
import java.net.Socket;
public class ServerThread extends Thread {
Socket s = null;
public ServerThread(Socket s) {
super("ServerThread");
this.s = s;
}
public void run() {
try( PrintWriter pw = new PrintWriter(s.getOutputStream(), true);
BufferedReader stream = new BufferedReader(new InputStreamReader(s.getInputStream()));
BufferedReader write = new BufferedReader(new InputStreamReader(System.in))) {
System.out.println("In Server");
String in, out;
while ((in = stream.readLine()) != null) {
System.out.println("Msg 4m client: " + in);
if(in.equals("bye"))
break;
out = write.readLine();
pw.println(out);
}
} catch (IOException ex) {
ex.printStackTrace();
}
}
}
Observe the try-with-resources statement over here, We can initialize multiple Connections/Input-Output Streams here, All of the opened connection will automatically be closed as soon as the compiler returns from try statement.Also, Observe the while statement, it will keep on running until the client is sending messages, and will quit if the message is "bye".
Finally, a Client program that sends request to the server.
Client.java
import java.net.Socket;
import java.io.PrintWriter;
import java.io.BufferedReader;
import java.io.InputStreamReader;
import java.io.IOException;
class Client {
public static void main(String[] args) {
try( Socket s = new Socket("localhost", 3333);
PrintWriter pw = new PrintWriter(s.getOutputStream(), true);
BufferedReader stream = new BufferedReader(new InputStreamReader(s.getInputStream()));
BufferedReader write = new BufferedReader(new InputStreamReader(System.in)) ) {
System.out.println("In Client");
String in;
while ((in = write.readLine()) != null) {
pw.println(in);
if(in.equals("bye"))
break;
System.out.println("Msg 4m server: " + stream.readLine());
}
} catch(IOException e) {
System.err.println("Exception: " + e);
}
}
}
Notice, the while Statement here, it will loop until the user is entering messages, and if the message is "bye", it will quit.Rest of the program can be easily understood from above explanation.
I am trying to broadcast a message to multiple clients but could not do so. I tried saving the socket connections in an array list and using a for loop, i tried to broadcast the message but only the client who posted the message is receiving the reply from server.
Client Code:
import java.net.*;
import java.util.Scanner;
import org.json.simple.JSONObject;
import java.io.*;
public class TCPClient {
public static void main (String args[]) {
// arguments supply message and hostname
JSONObject clientObj=new JSONObject();
Socket s = null;
try{
int serverPort = 7899;
Scanner scan=new Scanner(System.in);
s = new Socket("127.0.0.1", serverPort);
System.out.println("Connection Established");
DataInputStream in = new DataInputStream( s.getInputStream());
DataOutputStream out =new DataOutputStream( s.getOutputStream());
while(true)
{
System.out.print(">");
String inputdata=scan.nextLine();
clientObj.put("ID",inputdata );
System.out.println("Sending data");
out.writeUTF(clientObj.toString()); // UTF is a string encoding see Sn. 4.4
String data = in.readUTF(); // read a line of data from the stream
System.out.println(data) ; //writing received data
}
}catch (UnknownHostException e) {
System.out.println("Socket:"+e.getMessage());
}catch (EOFException e){
System.out.println("EOF:"+e.getMessage());
}catch (IOException e){
System.out.println("readline:"+e.getMessage());
}finally {
if(s!=null) try {
s.close();
}catch (IOException e){
System.out.println("close:"+e.getMessage());
}
}
}
}
Server Code:
import java.net.*;
import java.util.ArrayList;
import org.json.simple.JSONObject;
import org.json.simple.parser.JSONParser;
import org.json.simple.parser.ParseException;
import java.io.*;
public class TCPServer {
static ArrayList<String> client=new ArrayList<String>();
static ArrayList<Socket> clientSock=new ArrayList<Socket>();
static int i = 0;
public static void main (String args[]) {
try{
int serverPort = 7899; // the server port
ServerSocket listenSocket = new ServerSocket(serverPort);
while(true) {
System.out.println("Server listening for a connection");
Socket clientSocket = listenSocket.accept();
i++;
System.out.println("Received connection " + i );
Connection c = new Connection(clientSocket);
client.add("guest"+i);
clientSock.add(clientSocket);
}
}
catch(IOException e)
{
System.out.println("Listen socket:"+e.getMessage());
}
}
public void display(String BroadMsg1)
{
for(int j=0;j<client.size();j++)
{
System.out.println(clientSock.get(j));
}
}
public void broadcast(String BroadMsg)
{
String clientName=null;
Socket cSock=null;
//DataInputStream inBroad;
DataOutputStream outBroad=null;
for(int j=0;j<client.size();j++)
{
clientName=client.get(j);
cSock=clientSock.get(j);
try{
outBroad=new DataOutputStream(cSock.getOutputStream());
outBroad.writeUTF(clientName+">"+BroadMsg);
}catch(Exception ex)
{
/*client.remove(j);
clientSock.remove(j);*/
System.out.println(ex.getMessage());
}
}
}
}
class Connection extends Thread {
TCPServer tcpser=new TCPServer();
DataInputStream in;
DataOutputStream out;
Socket clientSocket;
public Connection (Socket aClientSocket) {
try {
clientSocket = aClientSocket;
in = new DataInputStream( clientSocket.getInputStream());
out =new DataOutputStream( clientSocket.getOutputStream());
this.start();
} catch(IOException e) {
System.out.println("Connection:"+e.getMessage());
}
}
public void run(){
JSONObject serObj=new JSONObject();
JSONParser jParser=new JSONParser();
try { // an echo server
while(true)
{
System.out.println("server reading data");
String data = in.readUTF(); // read a line of data from the stream
try {
serObj=(JSONObject)jParser.parse(data); //parsing JSONObject
} catch (ParseException e) {
e.printStackTrace();
}
System.out.println("server writing data");
// tcpser.display(serObj.get("ID").toString());
tcpser.broadcast(serObj.get("ID").toString());
}}
catch (EOFException e){
System.out.println("EOF:"+e.getMessage());
} catch(IOException e) {
System.out.println("readline:"+e.getMessage());
} finally{
try {
clientSocket.close();
}catch (IOException e){/*close failed*/}
}
}
}
Can anyone please help me out to rectify the mistake.
Thanks in advance :)
After creating Client Socket with accept command in server, start a new Thread by passing this socket is parameter. In the new thread, open InputStream and process it.
Go through the list of all client sockets and send the message by opening OutputStream on respective socket
Have look at this example Socket Programming. You can look at java docs for alternative approach Broadcasting
1) Create client thread after adding to the list.
2)Print Exception stack trace in catch block to know exception.
3) replace cSock=clientSock.get(j); with Iterator to go through all sockets.
I am beginner to java and learning Socket Programming.I am using the basic chat server socket communication. I am having difficulty to print the server and client messages to the console window.
I would also implement this concept when i design my chat Server window UI and will update the char server intercommunication messages to my UI. I would like to know as how can I achieve that ?
Code for 1
Server.java
package ChApp;
import java.io.IOException;
import java.net.*;
public class Server {
public static void main(String[] args) throws Exception {
Socket s;
ServerSocket server = new ServerSocket(3900);
while(true)
{
s = server.accept();
ServerHandl handle1 = new ServerHandl(s);
Thread t1= new Thread(handle1);
t1.start();
System.out.println("Connection Succesful...");
server.close();
}
}
}
Serverhandl.java
package ChApp;
import java.io.*;
import java.net.*;
public class ServerHandl implements Runnable {
Socket s= null;
BufferedReader read;
PrintWriter write;
String msg="Server is sending a sample msg";
public ServerHandl(Socket s)
{
this.s = s;
}
public void run()
{
try {
write = new PrintWriter(s.getOutputStream());
write.println(msg);
read = new BufferedReader(new InputStreamReader(s.getInputStream()));
System.out.println(read.readLine());
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
finally{
try {
read.close();
write.close();
s.close();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
}
Client.java
package ChApp;
import java.io.*;
import java.net.*;
import java.util.Scanner;
public class Client {
public static void main(String[] args) throws IOException {
Socket s= null;
BufferedReader read;
PrintWriter write = null;
String h;
StringBuilder sb = new StringBuilder();
String sendmsg="Reply from client";
s= new Socket("localhost",3900);
read = new BufferedReader(new InputStreamReader(s.getInputStream()));
while((h=read.readLine())!=null)
{
sb.append(h);
}
write = new PrintWriter(s.getOutputStream(),true);
write.write(sendmsg);
write.flush();
s.close();
read.close();
write.close();
}
}
Your client is calling readLine() until it returns null, but your server is reading from the connection so it hasn't closed it yet, so the null will never arrive, so you're deadlocked.
Read one line from the server and then send a response, then close the socket. Have the server close the socket after it calls readLine().
I am trying to code a chat in my java software,
i have 2 eclipses running on my windows 7.
one of the eclipses includes a project "ServerListener" which contains a class Server.java
and the other eclipse includes a project "Client" and contains a class cl.java.
I am sending messages from my cl.java to the server.java
each time the server receives a message he send it back to the cl.java (the one i sent the message from) to make sure it's connected.
(THIS PART WORKS FINE sending message to the server and back from the server to the same client)
my question is :
how to let the server.java send the message to another client instead of the original client?
if i run another eclipse with the same project as "Client"
i want to the two eclipses to chat together
this is the Server.java:
import java.io.IOException;
import java.io.InputStream;
import java.io.ObjectInputStream;
import java.io.ObjectOutputStream;
import java.io.OutputStream;
import java.net.ServerSocket;
import java.net.Socket;
import java.util.ArrayList;
public class Server {
ServerSocket serverSocket;
ArrayList<ServerThread> allClients = new ArrayList<ServerThread>();
public static void main(String[] args) {
new Server();
}
public Server() {
// ServerSocket is only opened once !!!
try {
serverSocket = new ServerSocket(6000);
System.out.println("Waiting on port 6000...");
boolean connected = true;
// this method will block until a client will call me
while (connected) {
Socket singleClient = serverSocket.accept();
// add to the list
ServerThread myThread = new ServerThread(singleClient);
allClients.add(myThread);
myThread.start();
}
// here we also close the main server socket
serverSocket.close();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
class ServerThread extends Thread {
Socket threadSocket;
String msg;
boolean isClientConnected;
InputStream input;
ObjectInputStream ois;
OutputStream output;
ObjectOutputStream oos; // ObjectOutputStream
public ServerThread(Socket s) {
threadSocket = s;
}
public void sendText(String text) {
try {
oos.writeObject(text);
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
public void run() {
try {
input = threadSocket.getInputStream();
ois = new ObjectInputStream(input);
output = threadSocket.getOutputStream();
oos = new ObjectOutputStream(output);
// get the user name from the client and store
// it inside thread class for later use
//msg = (String) ois.readObject();
isClientConnected = true;
//System.out.println(msg);
for(ServerThread t:allClients)
t.sendText("User has connected...");
// send this information to all users
// dos.writeUTF(userName + " has connected..");
// for(ServerThread t:allClients)
// t.sendText(msg);
while (isClientConnected) {
System.out.println("connect ... ");
try {
msg = (String) ois.readObject();
System.out.println(msg);
if (msg.equals("quit"))
break;
for (ServerThread t : allClients)
t.sendText(msg);
} catch (Exception e) {
}
}
// close all resources (streams and sockets)
ois.close();
oos.close();
threadSocket.close();
} catch (Exception e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
}
this is the client (cl.java):
import java.io.*;
import java.net.Socket;
import java.net.UnknownHostException;
import java.util.Scanner;
public class cl {
public static final String HOST = "127.0.0.1";
public static final int PORT = 6000;
static ConnectThread clientThread;
boolean isConnected;
static boolean isOnline = false;
static Scanner scanner = new Scanner(System.in);
static String msg;
public static void main(String[] args) {
new cl();
}
public cl() {
connectUser();
}
public void connectUser() {
clientThread = new ConnectThread();
clientThread.start();
}
class ConnectThread extends Thread {
InputStream input;
OutputStream output;
ObjectOutputStream oos;
Socket s;
public void sendText(String text) {
try {
System.out.println("sending text to server..");
oos.writeObject(text);
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
public void run() {
try {
s = new Socket(HOST, PORT);
output = s.getOutputStream();
oos = new ObjectOutputStream(output);
isOnline = true;
isConnected = true;
new ListenThread(s).start();
while (isOnline) {
System.out.println("Enter a Text to send:");
msg = scanner.nextLine();
clientThread.sendText("amjad: " + msg);
}
} catch (UnknownHostException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
class ListenThread extends Thread {
Socket s;
InputStream input;
ObjectInputStream ois;
public ListenThread(Socket s) {
this.s = s;
try {
input = s.getInputStream();
ois = new ObjectInputStream(input);
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
public void run() {
while (isConnected) {
try {
final String inputMessage = (String) ois.readObject();
System.out.println(inputMessage);
} catch (Exception e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
}
}
thanks in advance