I created a J2me program for HttpConenction to http://www.google.com
But when I run I get an error
error 10054 during TCP read
In this I have just created a HttpConnection and reads a string from inputstream
In this an object of Httpconnection is made then the Inputstream is called which read from url ie http://www.google.com
Below is the code
import java.io.DataOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.io.PrintStream;
import javax.microedition.io.ConnectionNotFoundException;
import javax.microedition.io.Connector;
import javax.microedition.io.HttpConnection;
import javax.microedition.io.OutputConnection;
import javax.microedition.lcdui.Alert;
import javax.microedition.lcdui.AlertType;
import javax.microedition.lcdui.Command;
import javax.microedition.lcdui.CommandListener;
import javax.microedition.lcdui.Display;
import javax.microedition.lcdui.Displayable;
import javax.microedition.lcdui.Form;
import javax.microedition.midlet.MIDlet;
import javax.microedition.midlet.MIDletStateChangeException;
public class NetworkFile extends MIDlet implements CommandListener {
Form form;
Display display;
Command start,exit;
public NetworkFile() {
// TODO Auto-generated constructor stub
form=new Form(null);
exit=new Command("Exit",Command.EXIT, 0);
start=new Command("Start",Command.OK, 1);
form.addCommand(exit);
form.addCommand(start);
form.setCommandListener(this);
}
protected void destroyApp(boolean arg0) throws MIDletStateChangeException {
// TODO Auto-generated method stub
}
protected void pauseApp() {
// TODO Auto-generated method stub
}
protected void startApp() throws MIDletStateChangeException {
// TODO Auto-generated method stub
display=Display.getDisplay(this);
display.setCurrent(form);
}
public void commandAction(Command c, Displayable d) {
// TODO Auto-generated method stub
if (c==start) {
Abc t=new Abc(this);
t.start();
} else if(c==exit){
notifyDestroyed();
}
}
}
class Abc extends Thread
{
NetworkFile net1;
HttpConnection hs=null;
DataOutputStream requestOutputStream;
InputStream is=null;
StringBuffer sb=null;
Abc(NetworkFile net1)
{
this.net1=net1;
}
public void run()
{
try {
/*OutputConnection connection=(OutputConnection)Connector.open("file:///D:/lamp.txt;append=true",Connector.WRITE);
OutputStream out=connection.openOutputStream();
PrintStream output=new PrintStream(out);
output.println("Hi , This is a J2ME project ");
out.close();
connection.close();
Alert alert=new Alert("Alert", "Data Written", null, AlertType.INFO);
alert.setTimeout(Alert.FOREVER);
net1.display.setCurrent(alert);*/
System.out.println("Line 1");
hs = (HttpConnection)Connector.open("http://www.google.com",Connector.READ_WRITE, true);
System.out.println("Line 2");
hs.setRequestMethod(HttpConnection.POST);
System.out.println("Line 3");
is=hs.openInputStream();
System.out.println("Line 4");
int ch=0;
sb = new StringBuffer();
for (int i = 0; i < 150; i++) {
System.out.println("Line 5");
ch=is.read();
System.out.println("Line 6");
if(ch==-1)
{
break;
}
System.out.println("ch "+ch);
sb.append((char)ch);
}
} catch (ConnectionNotFoundException e) {
// TODO Auto-generated catch block
System.out.println(e.toString());
Alert alert=new Alert("Alert", " Connection ERROR !!! "+e.toString(), null, AlertType.INFO);
alert.setTimeout(Alert.FOREVER);
net1.display.setCurrent(alert);
} catch (IOException e) {
System.out.println(e.toString());
// TODO Auto-generated catch block
Alert alert=new Alert("Alert", " IO ERROR !!! "+e.toString(), null, AlertType.INFO);
alert.setTimeout(Alert.FOREVER);
net1.display.setCurrent(alert);
}catch (Exception e) {
// TODO Auto-generated catch block
System.out.println(e.toString());
Alert alert=new Alert("Alert", " Exception ERROR !!! "+e.toString(), null, AlertType.INFO);
alert.setTimeout(Alert.FOREVER);
net1.display.setCurrent(alert);
}
System.out.println(sb.toString());
}
}
Related
I have A one RCP application which is run on the windows platform.in this application so many command in tool bar, So i want to assign one short cut key
to open one by one tool bar how to do this?
I have used key biding concept but, tool bar item = shortcut key happen , so i want only one key then how to do it possible?
You can't do this. A key binding is always bound to a single command.
If you want to do things in a sequence use a Wizard with multiple pages or something like that.
Using a cheat sheet to guide the user through the actions might be another way.
I have do it but different way. Whole toolbar item is passed via handler. I can share you code:
Forward Editor code:
package handler;
import org.eclipse.core.commands.AbstractHandler;
import org.eclipse.core.commands.ExecutionEvent;
import org.eclipse.core.commands.ExecutionException;
import org.eclipse.ui.IEditorReference;
import org.eclipse.ui.IWorkbenchPage;
import org.eclipse.ui.IWorkbenchWindow;
import org.eclipse.ui.PartInitException;
import org.eclipse.ui.handlers.HandlerUtil;
import rcp_demo.Editor.EmployeeEditor;
import rcp_demo.Editor.EmployeeEditorInput;
import rcp_demo.Editor.EnquiryEditor;
import rcp_demo.Editor.EnquiryEditorInput;
import rcp_demo.Editor.FoodDetailsEditor;
import rcp_demo.Editor.FoodDetailsEditorInput;
import rcp_demo.Editor.StaffdetailsEditor;
import rcp_demo.Editor.StaffdetailsEditorInput;
//Defauklt Editor ID
import rcp_demo.Editor.UserEditor;
import rcp_demo.Editor.UserEditorInput;
/**
* #author summet
*
*/
public class SwitchingHandler extends AbstractHandler {
/*
* (non-Javadoc)
*
* #see
* org.eclipse.core.commands.IHandler#execute(org.eclipse.core.commands.
* ExecutionEvent)
*/
String tempEditorID = null;
#Override
public Object execute(ExecutionEvent event) throws ExecutionException {
System.out.println("SwitchingHandler command call");
// TODO Auto-generated method stub
// HandlerUtil.getActiveWorkbenchWindow
IWorkbenchWindow window = HandlerUtil.getActiveWorkbenchWindow(event);
IWorkbenchPage page = window.getActivePage();
IEditorReference[] editorRefs = page.getEditorReferences();
// get the editor instance by given id (pEditorId)
if (page.getActiveEditor() == null || page.getActiveEditor().equals("")) {
// Default Editor Open via command
UserEditorInput input = new UserEditorInput();
try {
page.openEditor(input, UserEditor.ID);
} catch (PartInitException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
return null;
} else {
// First check Temp ID;
String tempID = checkActiveEditorID(page);
if (tempID.equals(UserEditor.BID)) {
System.out.println("You are in UserEditor.ID");
page.closeAllEditors(true);
EmployeeEditorInput einput = new EmployeeEditorInput();
try {
page.closeAllEditors(true);
page.openEditor(einput, EmployeeEditor.ID);
tempID = null;
} catch (PartInitException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
} else if (tempID.equals(EmployeeEditor.BID)) {
System.out.println("You are in EmployeeEditor.ID");
StaffdetailsEditorInput sinput = new StaffdetailsEditorInput();
try {
page.closeAllEditors(true);
page.openEditor(sinput, StaffdetailsEditor.ID);
tempID = null;
} catch (PartInitException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
} else if (tempID.equals(StaffdetailsEditor.BID)) {
System.out.println("You are in StaffdetailsEditor.ID");
FoodDetailsEditorInput finput = new FoodDetailsEditorInput();
try {
page.closeAllEditors(true);
page.openEditor(finput, FoodDetailsEditor.ID);
tempID = null;
} catch (PartInitException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
} else if (tempID.equals(FoodDetailsEditor.BID)) {
System.out.println("You are in FoodDetailsEditor.ID");
EnquiryEditorInput eeinput = new EnquiryEditorInput();
try {
page.closeAllEditors(true);
page.openEditor(eeinput, EnquiryEditor.ID);
tempID = null;
} catch (PartInitException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
} else if (tempID.equals(EnquiryEditor.BID)) {
System.out.println("You are in EnquiryEditor.ID");
UserEditorInput uinput = new UserEditorInput();
try {
page.closeAllEditors(true);
page.openEditor(uinput, UserEditor.ID);
tempID = null;
} catch (PartInitException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
return null;
}
private String checkActiveEditorID(IWorkbenchPage page) {
tempEditorID = page.getActiveEditor().getTitle();
return tempEditorID;
// TODO Auto-generated method stub
}
}
Backward Editor code:
package handler;
import org.eclipse.core.commands.AbstractHandler;
import org.eclipse.core.commands.ExecutionEvent;
import org.eclipse.core.commands.ExecutionException;
import org.eclipse.ui.IEditorReference;
import org.eclipse.ui.IWorkbenchPage;
import org.eclipse.ui.IWorkbenchWindow;
import org.eclipse.ui.PartInitException;
import org.eclipse.ui.handlers.HandlerUtil;
import rcp_demo.Editor.EmployeeEditor;
import rcp_demo.Editor.EmployeeEditorInput;
import rcp_demo.Editor.EnquiryEditor;
import rcp_demo.Editor.EnquiryEditorInput;
import rcp_demo.Editor.FoodDetailsEditor;
import rcp_demo.Editor.FoodDetailsEditorInput;
import rcp_demo.Editor.StaffdetailsEditor;
import rcp_demo.Editor.StaffdetailsEditorInput;
import rcp_demo.Editor.UserEditor;
import rcp_demo.Editor.UserEditorInput;
public class BackEditorHandler extends AbstractHandler {
/*
* (non-Javadoc)
*
* #see
* org.eclipse.core.commands.IHandler#execute(org.eclipse.core.commands.
* ExecutionEvent)
*/
String tempBackEditorID = null;
#Override
public Object execute(ExecutionEvent event) throws ExecutionException {
System.out.println("BackEditorHandler call");
// TODO Auto-generated method stub
IWorkbenchWindow window = HandlerUtil.getActiveWorkbenchWindow(event);
IWorkbenchPage page = window.getActivePage();
IEditorReference[] editorRefs = page.getEditorReferences();
// get the editor instance by given id (pEditorId)
if (page.getActiveEditor() == null || page.getActiveEditor().equals("")) {
// Default Editor Open via command
UserEditorInput input = new UserEditorInput();
try {
page.openEditor(input, UserEditor.ID);
} catch (PartInitException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
return null;
} else {
// First check Temp ID;
String tempBackID = checkActiveEditorID(page);
System.out.println("tempID:--" + tempBackID);
if (tempBackID.equals(UserEditor.BID)) {
System.out.println("You are in UserEditor.ID");
page.closeAllEditors(true);
EnquiryEditorInput eeinput = new EnquiryEditorInput();
try {
page.closeAllEditors(true);
page.openEditor(eeinput, EnquiryEditor.ID);
tempBackID = null;
} catch (PartInitException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
} else if (tempBackID.equals(EmployeeEditor.BID)) {
System.out.println("You are in EmployeeEditor.ID");
UserEditorInput uinput = new UserEditorInput();
try {
page.closeAllEditors(true);
page.openEditor(uinput, UserEditor.ID);
tempBackID = null;
} catch (PartInitException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
} else if (tempBackID.equals(StaffdetailsEditor.BID)) {
System.out.println("You are in StaffdetailsEditor.ID");
EmployeeEditorInput einput = new EmployeeEditorInput();
try {
page.closeAllEditors(true);
page.openEditor(einput, EmployeeEditor.ID);
tempBackID = null;
} catch (PartInitException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
} else if (tempBackID.equals(FoodDetailsEditor.BID)) {
System.out.println("You are in FoodDetailsEditor.ID");
StaffdetailsEditorInput sinput = new StaffdetailsEditorInput();
try {
page.closeAllEditors(true);
page.openEditor(sinput, StaffdetailsEditor.ID);
tempBackID = null;
} catch (PartInitException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
} else if (tempBackID.equals(EnquiryEditor.BID)) {
System.out.println("You are in EnquiryEditor.ID");
FoodDetailsEditorInput finput = new FoodDetailsEditorInput();
try {
page.closeAllEditors(true);
page.openEditor(finput, FoodDetailsEditor.ID);
tempBackID = null;
} catch (PartInitException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
return null;
}
private String checkActiveEditorID(IWorkbenchPage page) {
tempBackEditorID = page.getActiveEditor().getTitle();
return tempBackEditorID;
// TODO Auto-generated method stub
}
}
I have created MDB to pick the message from MQ and inserting in to DB2.
I have created data sourse to get the DB connection in WAS. Its inserting message. But due to the speed of the MessageListener some messages not inserted because the connection got closed..
Please help me to handle the conction here..
import java.sql.Connection;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;
import javax.ejb.ActivationConfigProperty;
import javax.ejb.MessageDriven;
import javax.jms.JMSException;
import javax.jms.Message;
import javax.jms.MessageListener;
import javax.jms.TextMessage;
import javax.naming.NamingException;
#MessageDriven(
activationConfig = { #ActivationConfigProperty(
propertyName = "destinationType", propertyValue = "javax.jms.Queue"), #ActivationConfigProperty(
propertyName = "destination", propertyValue = "jms/MDBQueue")
},
mappedName = "jms/MDBQueue")
public class AsyncMessageConsumerBean implements MessageListener {
// TODO Auto-generated constructor stub
private javax.naming.InitialContext ctx = null;
private javax.sql.DataSource serviceDataSource = null;
private String environment = null;
/**
* #see MessageListener#onMessage(Message)
*/
public void onMessage(Message message) {
// TODO Auto-generated method stub
System.out.println("On Message Started.....");
try{
if (message instanceof javax.jms.BytesMessage)
{
javax.jms.BytesMessage bytesMessage = (javax.jms.BytesMessage) message;
byte[] bytes = new byte[(int) bytesMessage.getBodyLength()];
bytesMessage.readBytes(bytes);
System.out.println("Reply Message");
String replyMessage = new String(bytes, "UTF-8");
System.out.println(" The message received from MQ :-----" + replyMessage);
insertMQMessage(replyMessage);
}else {
javax.jms.TextMessage TextMessage = (javax.jms.TextMessage) message;
System.out.println("----------- The text message received from UM Queue"+TextMessage.getText());
insertMQMessage(TextMessage.getText());
}
}catch (JMSException ex) {
throw new RuntimeException(ex);
}catch(Exception ex){
ex.printStackTrace();
}
}
public void insertMQMessage(String mqMessage) throws Exception
{
Statement stmtsql = null;
Connection connection = null;
try
{
connection = getDBConnection();
System.out.println("Connection Object :"+connection);
String mqMsgTrackerInsertQry = "";
System.out.println("MQ Tracker insert Query:" + mqMsgTrackerInsertQry);
stmtsql = connection.createStatement();
boolean status = stmtsql.execute(mqMsgTrackerInsertQry);
}
catch(Exception e)
{
e.printStackTrace();
throw e;
}
finally
{
if (stmtsql != null)
try {
stmtsql.close();
} catch (SQLException ignore) {
}
if (connection != null)
try {
connection.close();
} catch (SQLException ignore) {
}
}
}
private Connection getDBConnection() throws SQLException {
try {
ctx = new javax.naming.InitialContext();
serviceDataSource = (javax.sql.DataSource) ctx.lookup("jdbc/DB_DS_XA");
System.out.println("Datasource initiallised"+serviceDataSource);
} catch (NamingException e) {
System.out.println("peformanceappraisalstatus: COULDN'T CREATE CONNECTION!");
e.printStackTrace();
}
Connection connection = null;
try {
connection = serviceDataSource.getConnection();
//connection.setAutoCommit(false);
} catch (SQLException e) {
throw e;
}
return connection;
}
}
I have set up a network and I've set up the reading and writing stream to a socket as so:
//Set up socket reads and writes
final BufferedReader in = new BufferedReader(
new InputStreamReader(client.getInputStream()));
final PrintWriter out = new PrintWriter(
client.getOutputStream(), true);
I wanted to pass the two variables, 'in' and 'out', as parameters of another class' constructor. This is how it looks in the other class
BufferedReader in;
PrintWriter out;
public ClientThread(BufferedReader in, PrintWriter out) {
this.in = in;
this.out = out;
}
I then wanted to use those class variables to write to the output stream of the same socket like this (the class implements Runnable):
public void run() {
while (true) {
try {
String userCommand = in.readLine();
} catch (IOException e) {
// Die if something goes wrong.
System.err.println(e.toString());
System.exit(1);
}
}
}
However, whenever the code gets to this point, I get a SocketException:
java.net.SocketException: Socket closed
How can I fix this? I want to separate the setting up of the server and the socket from the processing of any commands given by the client.
EDIT: Here's what the BufferedRead gets the input from
//create server socket
ServerSocket server = new ServerSocket(portNum);
// Accept a client if it appears
Socket client = server.accept();
EDIT 2: I used these three files:
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.PrintWriter;
import java.net.Socket;
import java.net.UnknownHostException;
public class Client {
public static void main(String[] args) throws UnknownHostException, IOException {
//Change the socket if it doesn't work
Socket sock = new Socket("localhost", 5920);
//keyboard
final BufferedReader stdin = new BufferedReader(
new InputStreamReader(System.in));
//input from socket
final BufferedReader in = new BufferedReader(
new InputStreamReader(sock.getInputStream()));
//writer to socket
final PrintWriter out = new PrintWriter(
sock.getOutputStream(), true);
//new thread for incoming messages
(new Thread(){
#Override
public void run() {
String serverMessage;
try {
while ((serverMessage = in.readLine()) != null) {
System.out.println(serverMessage);
}
} catch (IOException e) {
System.err.println("Something went wrong whilst trying "
+ "to retrieve a message from the server");
System.exit(-1);
}
}
}).start();
//new thread for outgoing messages
(new Thread(){
#Override
public void run() {
String clientMessage;
try {
while ((clientMessage = stdin.readLine()) != null) {
out.println(clientMessage);
}
} catch (IOException e) {
System.err.println("Something went wrong whilst trying "
+ "to send a message to the server.");
System.exit(-1);
}
}
}).start();
}
}
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.PrintWriter;
import java.net.ServerSocket;
import java.net.Socket;
public class Server {
public static void main(String[] args) throws IOException {
ServerSocket server = new ServerSocket(5920);
Socket client = server.accept();
//Set up socket reads and writes
final BufferedReader in = new BufferedReader(
new InputStreamReader(client.getInputStream()));
final PrintWriter out = new PrintWriter(
client.getOutputStream(), true);
new Thread(new ClassWithParam(in, out)).start();
}
}
import java.io.BufferedReader;
import java.io.IOException;
import java.io.PrintWriter;
public class ClassWithParam implements Runnable {
BufferedReader in;
PrintWriter out;
public ClassWithParam(BufferedReader in, PrintWriter out) {
this.in = in;
this.out = out;
}
#Override
public void run() {
while (true) {
try {
System.out.println("HERE");
String userCommand = in.readLine();
System.out.println("HERE2");
} catch (IOException e) {
// Die if something goes wrong.
System.err.println(e.toString());
System.exit(1);
}
}
}
}
And now it works. Don't know what happened. Will proceed to bang head against wall. Thanks.
For some reason there's no problem now. The code (I recreated) which I used, which now works, is in the description.
I am currently writing this code for my client and server,
and I want to test it out using my emulator, but I'm stuck.
is this the correct IP address that I should be using?
socket = new Socket("10.0.2.2", 6000);
If i want to use my phone to test this out, what ip address should i be using?
thanks.
if you want to send messages between server/client, here is a sample code that i have made before.
please refer to the code below and feel free to comment!
also, that is the correct ip address to use when using emulator for simulation.
in addition, don't forget to change your permission to "android.permission.INTERNET" in your manifesto.
=================================myClient==================================
package com.example.myclient;
import java.io.IOException;
import java.io.ObjectInputStream;
import java.io.ObjectOutputStream;
import java.net.Socket;
import java.net.UnknownHostException;
import android.os.Bundle;
import android.app.Activity;
import android.util.Log;
import android.view.Menu;
import android.view.View;
import android.widget.Button;
public class MainActivity extends Activity {
/** Manifest --> uses permission --> "android.permission.INTERNET" */
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
Button btn = (Button) findViewById(R.id.btn);
btn.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
class MyThread extends Thread {
#Override
public void run() {
super.run();
Log.d("client", "thread is running...");
String str = "Do you want to eat hamburger?";
Socket socket;
try {
socket = new Socket("10.0.2.2", 6000);
ObjectOutputStream out = new ObjectOutputStream(socket
.getOutputStream());
ObjectInputStream in = new ObjectInputStream(
socket.getInputStream());
out.writeObject(str);
String rcv = (String) in.readObject();
Log.d("client", "Server :" + rcv);
out.close();
in.close();
socket.close();
} catch (UnknownHostException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (ClassNotFoundException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
MyThread t = new MyThread();
t.start();
}
});
}
}
============================MyServer========================================
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;
public class MyServer {
public static void main(String[] args) throws IOException, ClassNotFoundException {
ServerSocket server = new ServerSocket(6000);
System.out.println("waiting.....");
while (true) {
Socket socket = server.accept();
System.out.println("a client has connected...");
InputStream in = socket.getInputStream();
OutputStream out = socket.getOutputStream();
ObjectInputStream objIn = new ObjectInputStream(in);
ObjectOutputStream objOut = new ObjectOutputStream(out);
String str = (String) objIn.readObject();
System.out.println("client : " + str);
objOut.writeObject("No, I'm on a diet!!!");
objIn.close();
objOut.close();
socket.close();
}
}
}
10.0.2.2 will be the correct IP you are using emulator. 127.0.0.1 will be the IP if you are developing on the machine(client and server on same machine). As you said you want to test it in your mobile run the following code and you will get your IP(it will also work if you are on computer):
public class net
{
net() throws UnknownHostException
{
InetAddress ia=InetAddress.getLocalHost();
System.out.println(ia);
ia=InetAddress.getByName("local host");
System.out.println(ia);
}
public static void main(String args[])throws UnknownHostException
{
net a=new net();
}
}
The overall topic is actually like a Chat Application sending a simple string message to an aws server, which uses the message to make calculations server-side and sending a simple string message as a solution back to the client.
Server: I have written a Server Class and deployed it through eclipse to aws beanstalk. (see code Server)
Client: My android device creates a socket, establishes a successful connection to my aws beanstalk ip and 8080 port, while iterating through an endless while loop in a thread listening to incoming messages from the server. (see code Client and ClientThread)
Problem: My problem is that I don't know how to check whether the server receives the connection request and messages from the client. How do I make sure, that code on aws beanstalk actually runs in background continuously listening for incoming connections? I have deployed the code, does aws beanstalk automatically start the main method of the Server Class and runs it infinitely?
Here's the server code:
import java.io.BufferedInputStream;
import java.io.BufferedOutputStream;
import java.io.DataInputStream;
import java.io.DataOutputStream;
import java.io.IOException;
import java.net.ServerSocket;
import java.net.Socket;
public class Server {
public static void main(String args[]) {
ServerSocket server = null;
System.out.println("Trying to open serversocket!");
try {
server = new ServerSocket(8080);
} catch (IOException e) {
System.out.println("Error on port: 8080 " + ", " + e);
System.exit(1);
}
System.out
.println("Server setup and waiting for client connection ...");
Socket client = null;
try {
client = server.accept();
} catch (IOException e) {
System.out.println("Did not accept connection: " + e);
System.exit(1);
}
System.out
.println("Client connection accepted. Moving to local port ...");
try {
DataInputStream streamIn = new DataInputStream(
new BufferedInputStream(client.getInputStream()));
DataOutputStream streamOut = new DataOutputStream(
new BufferedOutputStream(client.getOutputStream()));
boolean done = false;
String line;
int i = 4;
while (!done) {
line = streamIn.readUTF();
if (line.equalsIgnoreCase(".bye"))
done = true;
else
System.out.println("Client says: " + line);
if (i == 4) {
streamOut
.writeUTF("Actually connected to Server with round "
+ i);
streamOut.flush();
i++;
}
}
streamIn.close();
streamOut.close();
client.close();
server.close();
} catch (IOException e) {
System.out.println("IO Error in streams " + e);
}
}
}
Here's the client code:
package com.amazon.aws.singlesensor;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.io.PrintWriter;
import java.net.Socket;
import java.net.UnknownHostException;
import android.util.Log;
class Client implements Runnable {
private Socket socket = null;
private InputStream streamIn = null;
private OutputStream streamOut = null;
public InputStream getStreamIn() {
return streamIn;
}
public Client(String serverName, int serverPort) {
System.out.println("Establishing connection. Please wait ...");
try {
socket = new Socket(serverName, serverPort);
Log.d("DEBUG", "Connected: " + socket);
start();
} catch (UnknownHostException uhe) {
Log.d("DEBUG", "Host unknown: " + uhe.getMessage());
} catch (IOException ioe) {
Log.d("DEBUG", "Unexpected exception: " + ioe.getMessage());
}
}
public void start() throws IOException {
streamIn = socket.getInputStream();
streamOut = socket.getOutputStream();
}
public void run() {
try {
streamOut.write(streamIn.read());
streamOut.flush();
} catch (IOException ioe) {
System.out.println("Sending error: " + ioe.getMessage());
stop();
}
}
public void handle(String msg) {
if (msg.equals(".bye")) {
System.out.println("Good bye. Press RETURN to exit ...");
stop();
} else
System.out.println(msg);
}
public void stop() {
try {
if (streamIn != null)
streamIn.close();
if (streamOut != null)
streamOut.close();
if (socket != null)
socket.close();
} catch (IOException ioe) {
System.out.println("Error closing ...");
}
}
public void send(String msg) {
PrintWriter printwriter = new PrintWriter(streamOut);
printwriter.write(msg);
printwriter.flush();
}
}
Here's the ClientThread Code
package com.amazon.aws.singlesensor;
import java.io.IOException;
import java.io.InputStream;
import android.os.Handler;
public class ClientThread extends Thread {
private Client client;
private InputStream input;
private String output;
private Handler handler;
private Runnable runner;
public ClientThread() {
}
public ClientThread(Client client, Handler handler, Runnable runner) {
this.setClient(client);
this.input = client.getStreamIn();
this.handler = handler;
this.runner = runner;
this.output = "";
}
public void run() {
int status = 0;
while (status != -1) {
try {
status = input.read();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
while (status != '~'){
try {
status = input.read();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
output = output + String.valueOf((char) status);
handler.post(runner);
}
output = output + "\n";
}
}
public String giveString(){
return output;
}
public void setClient(Client client) {
this.client = client;
}
public Client getClient() {
return client;
}
}
Thank you for your time!