Unable to send data to emulator from java through sockets - java

I run a service in android where i have a (server)socket and it listens to port 5587.I have a java (client)socket program which has to send data to the android emulator.But it cant send data to the emulator.I gave the ip address of the (server)i.e android emulator as 10.0.2.15.I also tried 10.0.0.3,10.0.0.4,10.0.0.5,10.0.0.6.But (client) java cant send data..it shows "connection timed out".My code is working fine if I give my phone ip address and run it on phone.I guess the ip address or port number is wrong.
My java program:
public class Main {
public static void main(String[] args) {
System.out.println("enter data to send to android");
mess = sc.nextLine();
try {
client = new Socket("10.0.2.15", 5587);
// emulator ip
oos = new ObjectOutputStream(client.getOutputStream());
oos.writeObject(mess);
ois = new ObjectInputStream(client.getInputStream());
message = (String) ois.readObject();
System.out.println("Message: " + message);
if(message == "Received"){
System.out.println("Message Sent Sucessfully");
}
else{
System.out.println("Message Not Sent...Try to resend");
}
//close resources
ois.close();
oos.close();
client.close();
Thread.sleep(1000);
} catch (IOException e) {
e.printStackTrace();
} catch (ClassNotFoundException e) {
e.printStackTrace();
} catch (InterruptedException e) {
e.printStackTrace();
}
My android code is also running perfect and it waits for the client
so below i post the code which is run by a new Thread inside the service
public void run() {
try {
server = new ServerSocket(port);// port = 5587 and ServerSocket intialised before itself
while (true) {
System.out.println("Waiting for client request");
Socket socket = server.accept();
//read from socket to ObjectInputStream object
ObjectInputStream ois = new ObjectInputStream(socket.getInputStream());
//convert ObjectInputStream object to String
String message = (String) ois.readObject();
Log.d("sri","Message Received: " + message);
} catch (IOException e) {
e.printStackTrace();
} catch (ClassNotFoundException e) {
e.printStackTrace();
}

Related

TCP client and server, cmd prompt using objectstreams

I have one client file clientRPC.java and server file serverRPC.java. Both communicate using TCP protocol and use objectinput and output stream to transfer data.
my client file:
public class clientRPC {
public static void main(String args[]) {
Socket s = null;
try {
int serverPort = 8888;
s = new Socket("localhost", serverPort);// server name is local host
//initializing input and output streams object and referencing them to get input and output
ObjectInputStream in = null;
ObjectOutputStream out = null;
out = new ObjectOutputStream(s.getOutputStream());
in = new ObjectInputStream(s.getInputStream());
MathsTutor mt = new MathsTutor();
out.writeObject(mt);
out.flush();
System.out.println("Welcome to Maths Tutor Service. The available maths exercises are:\n"
+ "Addition: Enter 'A' or 'a'\n"
+ "Subtraction: Enter 'S' or 's'\n"
+ "Multiplication: Enter 'M' or 'm'\n"
+ "Division: Enter 'D' or 'd'\n"
+ "Enter 'Q' or 'q' to quit");
//System.out.println();
MathsTutor mt1 = (MathsTutor) in.readObject();
String response = in.readUTF();
System.out.println(response);
} 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());
} catch (ClassNotFoundException ex) {
ex.printStackTrace();
} finally {
if (s != null) {
try {
s.close();
} catch (IOException e) {
System.out.println("close:" + e.getMessage());
}
}
}
}
}
and my server file :
public class serverRPC extends Thread {
String request;
String response;
public static void main(String args[]) {
try {
int serverPort = 8888;
ServerSocket listen_socket = new ServerSocket(serverPort);
while (true) {
Socket clientSocket = listen_socket.accept();
Connection c = new Connection(clientSocket);
}
} catch (IOException e) {
System.out.println("Listen socket:" + e.getMessage());
}
public serverRPC(String s) {
request = s;
}
}
class Connection extends Thread {
ObjectInputStream in;
ObjectOutputStream out;
Socket clientSocket;
public Connection(Socket aClientSocket) {
try {
clientSocket = aClientSocket;
in = new ObjectInputStream(clientSocket.getInputStream());
out = new ObjectOutputStream(clientSocket.getOutputStream());
this.start();
} catch (IOException e) {
System.out.println("Connection:" + e.getMessage());
}
}
public void run() {
try {
MathsTutor mt = (MathsTutor) in.readObject();
InetAddress ip = clientSocket.getInetAddress();
System.out.println("The Received Message from Client at address:/" + ip.getHostAddress());
System.out.println("====================================");
MathsTutor mt1 = new MathsTutor();
out.writeObject(mt1);
while(true) {
// Read from input
String command = in.readUTF();
System.out.println(command);
}
//System.out.println();
} catch (EOFException e) {
System.out.println("EOF:" + e.getMessage());
} catch (IOException e) {
System.out.println("readline:" + e.getMessage());
} catch (ClassNotFoundException ex) {
ex.printStackTrace();
} finally {
try {
clientSocket.close();
} catch (IOException e) {/*close failed*/
}
}
}
}
The problem is when I run server and then client on cmd, the client side displays the welcome msg and puts cursor on another line for user input but, I can't type anything, the cursor just blinks... I know this might be simple but it has taken already 3 hours for me and I'm stuck in the same thing.
The cursor marked with red keeps blinking but doesn't let me type anything.
You're writing an object with writeObject() and trying to read it with readUTF(). Illogical.
objects written with writeObject() must be read with readObject().
strings written with writeUTF() must be read with readUTF().
primitives written with writeXXX() must be read with readXXX(), for most values of X.

ObjectOutputStream in client causes ServerException

I have a client-server application. Right now, I'm trying to test sending messages from the client to the server and then read them from the server. I'm using ObjectInputStream and ObjectOutputStream to transfer message objects between the client and server.
However, when I try to write an object from the client, it results in a SocketException.
Server code:
while (true) {
try {
log.trace("Waiting for connection.");
Socket clientSocket = socket.accept();
log.trace("Socket connected");
/* create thread */
new Thread(new RequestRunner(clientSocket, serverID)).start();
} catch (SocketTimeoutException e) {
log.trace("Socket timed out.");
socket.close();
break;
} catch (IOException e) {
log.error("Cannot accept connection...");
break;
}
}
Server Thread:
public class RequestRunner implements Runnable {
....
public RequestRunner(Socket socket, UUID serverID) {
client = socket;
this.serverID = serverID;
}
/**
* Start the thread for the request
*/
public void run() {
log.trace("Thread started for socket");
try {
out = new ObjectOutputStream(client.getOutputStream());
in = new ObjectInputStream(client.getInputStream());
} catch (IOException e) {
log.error("Cannot intialize streams...");
return;
}
while(client.isConnected()) {
/* initialize streams */
try {
/* read message */
Object obj = in.readObject(); // does not block
MessageFrame msg = (MessageFrame) obj;
processRequest(msg);
} catch (IOException e) {
; // triggers everytime
//log.error("IO error occured while trying to get input/output stream from socket");
} catch (ClassNotFoundException e) {
log.error("Cannot read MessageFrame");
}
}
}
}
Client code:
public void init(int port) throws IOException {
log.trace("intializing to port " + port);
clientID = UUID.randomUUID();
socket = new Socket("0.0.0.0",port);
out = new ObjectOutputStream(socket.getOutputStream());
in = new ObjectInputStream(socket.getInputStream());
}
public void sendEcho() throws Exception {
while(socket.isConnected()) {
try {
log.trace("Sending echo..");
msg = new EchoMessage(clientID);
curMsgID = msg.getMsgID();
out.writeObject(msg); // throws SocketException, socket closed
out.flush();
break;
} catch (SocketException e) {
log.error ("Cannot send echo.. socket closed.");
break;
} catch (IOException e) {
continue;
}
}
}
The statement out.writeObject(msg) causes a ServerSocket exception with Socket closed as the reason. And the server does not register receiving an object from in.readObject().
netstat shows the connection as established, the error occurs when I try to write the object.
What am I doing wrong ?
You should only have one InputStream and one OutputStream.
out = new ObjectOutputStream(client.getOutputStream());
in = new ObjectInputStream(client.getInputStream());
Should be:
out = client.getOutputStream();
in = client.getInputStream()
And you should change it in the client code when getting the streams from the sockets as well.

java check if tcp socket is alive?

I am using the following code to read messages from a server:
Socket socket;
try {
socket = new Socket(InetAddress.getByName("url.com"), 8080);
is = new DataInputStream(socket.getInputStream());
os = new DataOutputStream(socket.getOutputStream());
} catch (IOException ex) {
Logger.getLogger(Client.class.getName()).log(Level.SEVERE, null, ex);
JOptionPane.showMessageDialog(rootPane,
"Could not establish network connection to the server." + " \nPlease check your internet connection and restart the application.",
"Unable to connect",
JOptionPane.INFORMATION_MESSAGE);
WindowEvent wev = new WindowEvent(this, WindowEvent.WINDOW_CLOSING);
Toolkit.getDefaultToolkit().getSystemEventQueue().postEvent(wev);
setVisible(false);
dispose();
System.exit(0);
}
// Start thread to listen for messages from the server
new ListenFromServer().start();
/*
* Thread class to listen for message from the server
*/
class ListenFromServer extends Thread {
public void run() {
BufferedReader in = new BufferedReader(new InputStreamReader(is));
while (true) {
try {
String tmpMsg = in .readLine().replaceAll("\\r\\n|\\r|\\n", "");
JSONObject json = new JSONObject(tmpMsg);
if (json.get("type").toString().contains("preview")) {
System.out.println("PREVIEW: " + json.get("msg").toString());
}
} catch (Exception e) {
e.printStackTrace();
}
}
}
}
How can i detect if the connection drops? For example if the server crashes?
Please do not use DataInputStream or DataOutputStream for text. You don't need them and they add confusion.
To detect a server has gone you need to send a piece of data and get a response. If you don't with a certain time, the connection or service is lost.

client creates new socket object everytime the server is on

i've done a socket programming with client residing on android and server residing on the desktop ....... whenever server is down as we know client lost the connection.....so it undergoes a looping until it connects to server.......
here the problem is in the below code
tabletclient = new Socket(SERVER_IP, TAB_SERVER_PORT);
in the while loop in the case of lost connection.........but when the connection is on it again creates a new object........
can anyone please tell me how to solve this problem..........
In the client side
while(true){
try {
tabletclient = new Socket(SERVER_IP, TAB_SERVER_PORT);
tabletout = new PrintWriter(tabletclient.getOutputStream());
in = new Scanner(tabletclient.getInputStream());
try
{
if((line = in.nextLine())!=null)
{
// my task to be done
}
}catch(Exception d){
System.out.println("Connection from server has lost.........tabletclient.isConnected()----->"+tabletclient.isConnected());
}
} catch (UnknownHostException e) { System.out.println("Entered 2.........");
} catch (IOException e) { System.out.println("Entered 3.........");e.printStackTrace();
}
}
In in the Server side
:
:
private Set <Socket> TABhs=new HashSet<Socket>();
:
:
new Thread(new TABServerThread()).start(); // runs in background
:
:
:
class ServerThread implements Runnable {
private ServerSocket server;
#Override
public void run() {
try {
server = new ServerSocket(SERVER_PORT);
System.out.println("Server Start the server at port " + SERVER_PORT
+ " and waiting for clients...");
while (true) {
Socket socket = server.accept();
System.out.println("Server Accept socket connection: "
+ socket.getLocalAddress());
new Thread(new ClientHandler(socket)).start();
}
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
private static PrintWriter out;
class ClientHandler implements Runnable {
private Socket clientSocket;
private Scanner in;
public ClientHandler(Socket clietSocket) {
this.clientSocket = clietSocket;
}
#Override
public void run() {
try {
out = new PrintWriter(clientSocket.getOutputStream());
in = new Scanner(clientSocket.getInputStream());
String line;
System.out.println("ClientHandlerThread Start communication with : "+ clientSocket.getLocalAddress());
try{
while((line = in.nextLine()) != null) {
System.out.println("ClientHandlerThread Client says: " + line);
String dat[]=line.split("#");
String query="insert into table_orders (tableno,kotno, orders,status) values('"+dat[1]+"','"+dat[0]+"','"+dat[2]+"','pending')";
try {
int i= dbGetDet.insertDetails(query);
if(i>0)
{
fillTable();
filtercomboBox();
out.print("success");
out.flush();
for(Socket so:TABhs)
{
PrintWriter ot = new PrintWriter(so.getOutputStream());
ot.println("tableallocation#"+dat[1]);
ot.flush();
}
System.out.println("SENDED 'SUCCESS' TO CLIENT");
}
} catch (Exception ex) {
Logger.getLogger(MYClientclass.class.getName()).log(Level.SEVERE, null, ex);
}
// }
}
}catch(Exception r){}
} catch (IOException e) {
e.printStackTrace();
}
}
}
In the Button click of server
String stat=status_combo.getSelectedItem().toString();
String tables=tableno_combo.getSelectedItem().toString();
String kotno=kotno_combo.getSelectedItem().toString();
if(stat.equals("Processing"))
{
try {
TABhs = new CopyOnWriteArraySet(TABhs);
int soint=1;
System.out.println("TABhs Processing--------------------->"+TABhs.size());
for(Iterator <Socket> it=TABhs.iterator();it.hasNext();)
{
Socket so=it.next();
System.out.println("SEEE SOCKET Processing"+soint+"----->"+so.isClosed());
PrintWriter ot = new PrintWriter(so.getOutputStream());
ot.println("tableupdate#"+tables+"#"+kotno+"#processing");
ot.flush();
JOptionPane.showMessageDialog(rootPane, "<html><body>Table Kot Status Changed to <b>Processing</b></body></html>");
soint++;
}
System.out.println("TABhs Processing--------------------->"+TABhs.size());
}
catch (Exception ex) {
Logger.getLogger(MYClientclass.class.getName()).log(Level.SEVERE, null, ex);
}
}
NOW EACH TIME WHEN BUTTON IS CLICKED THE OUTPUT IS AS GIVEN BELOW
FISRT CLICK
SEEE SOCKET Ready 1----->false
Server Accept socket connection: /192.168.1.74
SEEE SOCKET Ready 2----->false
TABhs--------------------->2
SECOND CLICK
SEEE SOCKET Ready 1----->false
SEEE SOCKET Ready 2----->false
Server Accept socket connection: /192.168.1.74
SEEE SOCKET Ready 3----->false
TABhs--------------------->4
FOURTH CLICK
SEEE SOCKET Ready 1----->false
SEEE SOCKET Ready 2----->false
SEEE SOCKET Ready 3----->false
Server Accept socket connection: /192.168.1.74
SEEE SOCKET Ready 4----->false
TABhs--------------------->5
I think the problem is at the client's side you read a line and then create a new connection.
I think you must keep reading the socket until it's closed or an error occurs.
For example:
while (true)
{
tabletclient = null;
int loop = 0;
// loop until a connection is established
while (tabletclient == null)
{
try
{
tabletclient = new Socket(SERVER_IP, TAB_SERVER_PORT);
}
catch (Exception e)
{
e.printStackTrace();
// set the value to quit when no connection could be established
if (loop++ > 100)
return;
}
}
try
{
tabletout = new PrintWriter(tabletclient.getOutputStream());
in = new Scanner(tabletclient.getInputStream());
// read the socket until it's closed or an error occurs
try
{
while ((line = in.nextLine()) != null)
{
// my task to be done
}
}
catch (Exception d)
{
System.out.println("Connection from server has lost.........tabletclient.isConnected()----->"
+ tabletclient.isConnected());
}
tabletsocket.close();
}
catch (UnknownHostException e)
{
System.out.println("Entered 2.........");
}
catch (IOException e)
{
System.out.println("Entered 3.........");
e.printStackTrace();
}
}
Also, you must close the server side when the transfer from the server to the client is completed.

Java Client/Server Socket Broken Pipe

I'm creating an update client via Sockets and I'm getting a Broken Pipe on the server side. The server accepts a client socket and responds to the same socket with either a message or a large byte array (~180MB). The error does not happen when testing locally (both client and server on the same machine) and it seems that it happens while sending the byte array. I'm not specifying a time out on the client socket and don't know why it is closing before reading the full response. Its my first time working with sockets and any help would be appreciated.
My Client Socket Code:
public static Response makeRequest(Request req) throws IOException {
Response response = null;
Socket echoSocket = null;
ObjectOutputStream out = null;
ObjectInputStream in = null;
echoSocket = new Socket(serverHost, 10008);
out = new ObjectOutputStream(echoSocket.getOutputStream());
in = new ObjectInputStream(
echoSocket.getInputStream());
BufferedReader stdIn = new BufferedReader(
new InputStreamReader(System.in));
out.writeObject(req);
try {
response = (Response)in.readObject();
} catch (ClassNotFoundException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
out.close();
in.close();
stdIn.close();
echoSocket.close();
return response;
}
Response is just a POJO holding the response (string/byte[] and other data)
My Server Code (copied an example of Sun/Oracle site and added my code to it)
public class Server extends Thread {
private Socket clientSocket;
public Server(Socket clientSocket) {
this.clientSocket = clientSocket;
start();
}
public void run()
{
{
System.out.println ("New Communication Thread Started");
try {
ObjectOutputStream out = new ObjectOutputStream(clientSocket.getOutputStream());
ObjectInputStream in = new ObjectInputStream(clientSocket.getInputStream());
Request request = null;
try {
request = (Request)in.readObject();
} catch (ClassNotFoundException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
UpdateDAO dao = new UpdateDAO();
ClientDAO cdao = new ClientDAO();
Update update = null;
Client client = null;
Session s = HibernateUtil.currentSession();
Transaction t = s.beginTransaction();
if (request != null) {
client = cdao.getClient(request.getClientId());
LogItem log = new LogItem();
log.setClient(client);
log.setTimestamp(new Date());
log.setAction(request.getAction());
if (request.getResponse() != null) {
update = dao.getUpdate(request.getResponse().getUpdateId());
}
TaskContext ctx = new TaskContext(request, client, update, log);
System.out.println("Action: " + request.getAction().getDescription());
Task task = TaskFactory.getTask(request.getAction());
System.out.println(task.getClass().getName());
Response response = task.perform(ctx);
out.writeObject(response);
log.setClientTaskDescription(request.getMessage());
log.setUpdate(ctx.getUpdate());
dao.save(ctx.getLog());
if (ctx.getUpdate() != null) {
dao.update(ctx.getUpdate());
}
} else {
out.writeObject(new Response("what"));
}
t.commit();
out.close();
in.close();
clientSocket.close();
}
catch (IOException e)
{
e.printStackTrace();
System.exit(1);
}
}
}
public static void main(String[] args) throws IOException
{
ServerSocket serverSocket = null;
try {
serverSocket = new ServerSocket(10008);
System.out.println ("Connection Socket Created");
try {
while (true)
{
System.out.println ("Waiting for Connection");
new Server (serverSocket.accept());
}
}
catch (IOException e)
{
System.err.println("Accept failed.");
System.exit(1);
}
}
catch (IOException e)
{
System.err.println("Could not listen on port: 10008.");
System.exit(1);
}
finally
{
try {
serverSocket.close();
}
catch (IOException e)
{
System.err.println("Could not close port: 10008.");
System.exit(1);
}
}
}
}
If the client is, in fact, running out of memory:
java -Xmx512m -jar <the jar>
or
java -Xmx512m com.foo.blah.YourClass
would increase the maximum heap for the client/server. Keep in mind you may have to increase the heap for both sides of the pipe since both sides would be reading all ~180mb into memory at runtime.

Categories

Resources