Selenium UnreachableBrowserException - “Could not start a new session” in Eclipse - eclipse

When I try to connect to facebook.com through PhantomJS I receive this error. I could not find a solution.
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.phantomjs.PhantomJSDriver;
import org.openqa.selenium.phantomjs.PhantomJSDriverService;
import org.openqa.selenium.remote.DesiredCapabilities;
public class SeleniumDemo {
public static void main(String[] args) throws Exception {
// TODO Auto-generated method stub
DesiredCapabilities caps = new DesiredCapabilities();
caps.setJavascriptEnabled(true);
caps.setCapability(PhantomJSDriverService.PHANTOMJS_EXECUTABLE_PATH_PROPERTY, "E:/ProjectTrials/phantomjs-2.1.1-windows/phantomjs-2.1.1-windows/bin/phantomjs.exe");
System.out.println("c1");
WebDriver driver = new PhantomJSDriver(caps);
System.out.println("c2");
driver.get("https://www.facebook.com");
System.out.println("c3");
System.out.println("Page Title: " + driver.getTitle());
}
}

Related

getting variables from other files in the project (like from main class and from other .class file) [duplicate]

This question already has answers here:
Passing Parameters JavaFX FXML
(10 answers)
Closed 5 years ago.
EDIT: Someone marked this as duplicate. I've read through the other question several times but I don't really understand how I can apply this to my program. It would be really nice if someone could help me in this specific context as I don't have much knowledge about Java yet. A short starting point would maybe even help me out. My question has nothing to do with a popup.
I have a problem. I don't wanna put the server code into the initialize() method of FXMLController. Instead I put the server start code into the start() method of MainApp and created a RemoteReader class. But how do I get the in and output stream variables from RemoteReader or MainApp into the FXMLController class? I'm using SceneBuilder.
Code:
FXMLController.java:
package de.freakyonline.ucone;
import de.freakyonline.ucone.Player;
import de.freakyonline.ucone.PlayerList;
import java.net.URL;
import java.util.ResourceBundle;
import javafx.application.Platform;
import javafx.event.ActionEvent;
import javafx.event.Event;
import javafx.fxml.FXML;
import javafx.geometry.Insets;
import javafx.scene.Scene;
import javafx.scene.control.ContextMenu;
import javafx.scene.control.Label;
import javafx.scene.control.MenuBar;
import javafx.scene.control.MenuItem;
import javafx.scene.control.Tab;
import javafx.scene.control.TableColumn;
import javafx.scene.control.TableView;
import javafx.scene.control.TextArea;
import javafx.scene.control.TextField;
import javafx.scene.control.Tooltip;
import javafx.scene.control.cell.PropertyValueFactory;
import javafx.scene.control.cell.TextFieldTableCell;
import javafx.scene.input.ContextMenuEvent;
import javafx.scene.input.InputMethodEvent;
import javafx.scene.input.KeyEvent;
import javafx.scene.layout.BorderPane;
import javafx.scene.layout.StackPane;
import javafx.scene.web.HTMLEditor;
import javafx.stage.Modality;
import javafx.stage.Stage;
public class FXMLController {
#FXML
private ResourceBundle resources;
#FXML
private URL location;
#FXML
private BorderPane borderPane;
#FXML
private TableView<Player> playerTable;
final Tooltip playerTableToolTip = new Tooltip("Rightclick for more options ...");
#FXML
private TableColumn<Player, String> nickColumn;
#FXML
private TableColumn<Player, String> groupColumn;
#FXML
private TableColumn<Player, String> yearOfBirthColumn;
#FXML
private TableColumn<Player, Integer> ageColumn;
#FXML
private TableColumn<Player, String> genderColumn;
#FXML
private TableColumn<Player, String> lastQuitColumn;
#FXML
private Tab consoleOneTab;
#FXML
private MenuBar mainMenuBar;
#FXML
private TextArea consoleOneTextArea;
#FXML
private TextField consoleOneTextField;
#FXML
void handleConsoleOneAction(ActionEvent event) {
switch(consoleOneTextField.getText().toLowerCase()) {
case "freaky":
consoleOneTextArea.appendText("Freaky rulez! :D\n");
break;
case "ky3ak":
consoleOneTextArea.appendText("Ky3ak rulez! :D\n");
break;
case "testserver":
consoleOneTextArea.appendText("Sending an object ...");
// PROBLEM: I don't know how I can get the out variable of remote (RemoteReader) to here.
remote.out.writeObject(new Player("freakyy85","Owner","1810",31,"m","missing..."));
case "help":
consoleOneTextArea.appendText("This console is mainly to log stuff which is done by the program to the user, so they can see what's going on.");
break;
default: consoleOneTextArea.appendText("Unknown Command\n");
}
consoleOneTextField.clear();
}
#FXML
void handleConsoleOneTabSelected(Event event) {
consoleOneTextField.requestFocus();
}
#FXML
void handleFileClose(ActionEvent event) {
Platform.exit();
}
#FXML
void handleHelpAbout(ActionEvent event) {
Stage haStage = new Stage();
haStage.setTitle("Help --> About");
Label aboutText = new Label("UCOne by freakyy85\nInitially developed for Ky3ak and UnityCraft");
aboutText.setPadding(new Insets(20));
haStage.setScene(new Scene(new StackPane(aboutText)));
haStage.initOwner(borderPane.getScene().getWindow());
haStage.initModality(Modality.WINDOW_MODAL);
haStage.show();
}
#FXML
void handlePlayerEditCommit(TableColumn.CellEditEvent<Player, String> event) {
System.out.println(event.getRowValue().toString());
}
#FXML
void handleTextChanged(InputMethodEvent event) {
}
#FXML
private void handlePTContextMenuRequest(ContextMenuEvent event) {
System.out.println("Target: " + event.getTarget().toString());
System.out.println("Source: " + event.getSource().toString());
final ContextMenu playerTableContextMenu = new ContextMenu();
MenuItem testMenuItem = new MenuItem("Test");
testMenuItem.setOnAction( e -> consoleOneTextArea.appendText("Used ContextMenu in Playertable, here: " + event.getTarget().toString()));
MenuItem colorizeFont = new MenuItem("Colorize Font");
colorizeFont.setOnAction( e -> consoleOneTextArea.appendText("PickResult: " + event.getPickResult().toString()));
MenuItem makeLocalNotes = new MenuItem("Local Player Notes");
makeLocalNotes.setOnAction( (e) -> {
Stage plnStage = new Stage();
plnStage.setTitle("(nickHere) - PlayerLocalNotesEditor");
HTMLEditor playerLocalNotes = new HTMLEditor();
plnStage.setScene(new Scene(new StackPane(playerLocalNotes)));
plnStage.initOwner(borderPane.getScene().getWindow());
plnStage.initModality(Modality.WINDOW_MODAL);
plnStage.show();
});
playerTableContextMenu.getItems().add(testMenuItem);
playerTableContextMenu.getItems().add(colorizeFont);
playerTableContextMenu.getItems().add(makeLocalNotes);
playerTableContextMenu.show(borderPane.getScene().getWindow(),event.getScreenX(),event.getScreenY());
}
#FXML
void initialize() {
assert nickColumn != null : "fx:id=\"nickColumn\" was not injected: check your FXML file 'Scene.fxml'.";
assert groupColumn != null : "fx:id=\"groupColumn\" was not injected: check your FXML file 'Scene.fxml'.";
PlayerList playerList = new PlayerList();
playerTable.setItems(playerList.playerList);
nickColumn.setCellValueFactory(new PropertyValueFactory<Player,String>("nick"));
groupColumn.setCellValueFactory(new PropertyValueFactory<Player,String>("group"));
yearOfBirthColumn.setCellValueFactory(new PropertyValueFactory<Player,String>("yearOfBirth"));
yearOfBirthColumn.setCellFactory(TextFieldTableCell.forTableColumn());
ageColumn.setCellValueFactory(new PropertyValueFactory<Player,Integer>("age"));
genderColumn.setCellValueFactory(new PropertyValueFactory<Player,String>("gender"));
genderColumn.setCellFactory(TextFieldTableCell.forTableColumn());
lastQuitColumn.setCellValueFactory(new PropertyValueFactory<Player,String>("lastQuit"));
playerTable.setTooltip(playerTableToolTip);
}
}
MainApp.java:
package de.freakyonline.ucone;
import java.io.ObjectInputStream;
import java.io.ObjectOutputStream;
import java.net.Socket;
import javafx.application.Application;
import static javafx.application.Application.launch;
import javafx.fxml.FXMLLoader;
import javafx.scene.Parent;
import javafx.scene.Scene;
import javafx.stage.Stage;
public class MainApp extends Application {
String ver = "v0.1-SNAPSHOT";
ObjectOutputStream out;
ObjectInputStream in;
#Override
public void start(Stage stage) throws Exception {
Parent root = FXMLLoader.load(getClass().getResource("/fxml/Scene.fxml"));
// Connect to Server
try {
Socket sock = new Socket("unitycraft.de", 2009);
out = new ObjectOutputStream(sock.getOutputStream());
in = new ObjectInputStream(sock.getInputStream());
// Listen for remote stuff comming in ...
Thread remote = new Thread(new RemoteReader(in,out,sock));
remote.start();
} catch (Exception ex) { ex.printStackTrace(); }
Scene scene = new Scene(root);
scene.getStylesheets().add("/styles/Styles.css");
stage.setTitle("UCOne - The UnityCraft Staff Tool " + ver);
stage.setScene(scene);
stage.show();
}
/**
* The main() method is ignored in correctly deployed JavaFX application.
* main() serves only as fallback in case the application can not be
* launched through deployment artifacts, e.g., in IDEs with limited FX
* support. NetBeans ignores main().
*
* #param args the command line arguments
*/
public static void main(String[] args) {
launch(args);
}
}
RemoteReader.java:
package de.freakyonline.ucone;
import java.io.ObjectInputStream;
import java.io.ObjectOutputStream;
import java.net.Socket;
/**
*
* #author uwe
*/
public class RemoteReader implements Runnable {
Object obj = null;
ObjectInputStream in;
ObjectOutputStream out;
Socket sock;
public RemoteReader (ObjectInputStream in, ObjectOutputStream out, Socket sock) {
this.in = in;
this.out = out;
this.sock = sock;
}
public void run() {
try {
while((obj=in.readObject()) != null)
System.out.println("Got object from server ...");
} catch (Exception ex) { ex.printStackTrace(); }
}
}
Btw, I'm currently learning. ;)
I got it working. I changed the main class to this:
public class MainApp extends Application {
String ver = "v0.1-SNAPSHOT";
ObjectOutputStream out;
ObjectInputStream in;
Socket sock;
Thread remote;
#Override
public void start(Stage stage) throws Exception {
FXMLLoader root = new FXMLLoader(
getClass().getResource("/fxml/Scene.fxml")
);
// Parent root = FXMLLoader.load(getClass().getResource("/fxml/Scene.fxml"));
// Connect to Server
try {
Socket sock = new Socket("unitycraft.de", 2009);
out = new ObjectOutputStream(sock.getOutputStream());
in = new ObjectInputStream(sock.getInputStream());
// Listen for remote stuff comming in ...
Thread remote = new Thread(new RemoteReader(in,out,sock));
remote.start();
} catch (Exception ex) { ex.printStackTrace(); }
Scene scene = new Scene(root.load());
scene.getStylesheets().add("/styles/Styles.css");
FXMLController controller = root.<FXMLController>getController();
controller.initData(in,out,sock);
// Connect to Server
try {
Socket sock = new Socket("unitycraft.de", 2009);
out = new ObjectOutputStream(sock.getOutputStream());
in = new ObjectInputStream(sock.getInputStream());
// Listen for remote stuff comming in ...
remote = new Thread(new RemoteReader(in,out,sock,controller.));
remote.start();
} catch (Exception ex) { ex.printStackTrace(); }
stage.setTitle("UCOne - The UnityCraft Staff Tool " + ver);
stage.setScene(scene);
stage.show();
}
/**
* The main() method is ignored in correctly deployed JavaFX application.
* main() serves only as fallback in case the application can not be
* launched through deployment artifacts, e.g., in IDEs with limited FX
* support. NetBeans ignores main().
*
* #param args the command line arguments
*/
public static void main(String[] args) {
launch(args);
}
}
And I added in FXMLController this method, plus the declaration of the class fields (in,out,sock):
void initData(ObjectInputStream in, ObjectOutputStream out, Socket sock) {
this.in = in;
this.out = out;
this.sock = sock;
}
Now I can access the output stream from within FXMLController. But now I can't access the textarea from within RemoteReader.java. I started a new question. ;)

JMS Consumer terminates and doesn't receive Message

So I'm following this youtube tutorial on Java Message Service with JBoss. My codes are the same to the video however when I run my TopicConsumer and TopicProducer applications, both terminates and don't stay alive for me to receive my message. I read that setMessageListener would have created a new thread so the message should be received even if the main thread was terminated but I'm still not receiving the message.
I found out that it's not calling onMessage, is it because TopicConsumer was terminated before it gets a chance to?
I've my JBoss 5.0 server running, just like in the video I run TopicConsumer first (but it terminates after the print statement unlike in the video) then TopicProduver (which also terminates right after the print statement) and I don't receive my message.
Thanks.
TopicConsumer.java
package jmspubsubtutorial;
import java.util.Properties;
import javax.jms.JMSException;
import javax.jms.Message;
import javax.jms.MessageListener;
import javax.jms.TextMessage;
import javax.jms.Topic;
import javax.jms.TopicConnection;
import javax.jms.TopicConnectionFactory;
import javax.jms.TopicSession;
import javax.naming.Context;
import javax.naming.InitialContext;
import javax.naming.NamingException;
public class TopicConsumer implements MessageListener {
public static void main(String[] args) throws JMSException, NamingException{
System.out.println("---Starting TopicConsumer---");
Context context = TopicConsumer.getInitialContext();
TopicConnectionFactory topicConnectionFactory = (TopicConnectionFactory) context.lookup("ConnectionFactory");
Topic topic = (Topic) context.lookup("topic/JMS_tutorial");
TopicConnection topicConnection = topicConnectionFactory.createTopicConnection();
TopicSession topicSession = topicConnection.createTopicSession(false, TopicSession.AUTO_ACKNOWLEDGE);
topicSession.createSubscriber(topic).setMessageListener(new TopicConsumer());
topicConnection.start();
System.out.println("---Exiting TopicConsumer---");
}
#Override
public void onMessage(Message message) {
System.out.println("--- onMessage ---");
try {
System.out.println("Incoming message: " + ((TextMessage)message).getText());
} catch (JMSException e) {
System.out.println("onMessage failed");
e.printStackTrace();
}
}
public static Context getInitialContext() throws JMSException, NamingException {
Properties props = new Properties();
props.setProperty("java.naming.factory.initial", "org.jnp.interfaces.NamingContextFactory");
props.setProperty("java.naming.factory.url.pkgs", "org.jboss.naming");
props.setProperty("java.naming.provider.url", "localhost:1099");
Context context = new InitialContext(props);
return context;
}
}
TopicProducer.java
package jmspubsubtutorial;
import javax.jms.JMSException;
import javax.jms.TextMessage;
import javax.jms.Topic;
import javax.jms.TopicConnection;
import javax.jms.TopicConnectionFactory;
import javax.jms.TopicPublisher;
import javax.jms.TopicSession;
import javax.naming.Context;
import javax.naming.NamingException;
public class TopicProducer {
public static void main(String[] args) throws JMSException, NamingException{
System.out.println("---Starting TopicProducer---");
Context context = TopicConsumer.getInitialContext();
TopicConnectionFactory topicConnectionFactory = (TopicConnectionFactory) context.lookup("ConnectionFactory");
Topic topic = (Topic) context.lookup("topic/JMS_tutorial");
TopicConnection topicConnection = topicConnectionFactory.createTopicConnection();
TopicSession topicSession = topicConnection.createTopicSession(false, TopicSession.AUTO_ACKNOWLEDGE);
topicConnection.start();
TopicProducer topicProducer = new TopicProducer();
String text = "message 1 from TopicProducer...";
topicProducer.sendMessage(text, topicSession, topic);
System.out.println("---Exiting TopicProducer---");
}
public void sendMessage(String text, TopicSession topicSession, Topic topic) throws JMSException {
System.out.println("Send Message: " + text + " " + topicSession + " " + topic);
TopicPublisher topicPublisher = topicSession.createPublisher(topic);
TextMessage textMessage = topicSession.createTextMessage(text);
topicPublisher.publish(textMessage);
topicPublisher.close();
}
}
So the problem is that you are relying on the JMS library to maintain at least one non-daemon thread in order to keep your application alive after you create the consumer and assign the message listener but in reality there is no guarantee that it will do any such thing.
It's true that many JMS providers do indeed attempt to always have a single non-daemon thread running internally but assuming that this will always be the case is not really advisable. You've seemed to find that the your particular provider does not do this for you, so if you want to ensure your application stays running you should make this happen yourself.

Eclipse Luna F6 doesn't step over

Strange, I have a Java application in Eclipse Luna and when debugging it and I'm trying to use F6 it doesn't "step over", but instead it "steps into".
I was trying to build a Java applicaton in Eclipse Luna. It was a database application from
here.
With two source files (DB.java):
`import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;
public class DB {
public Connection conn = null;
public DB() {
try {
Class.forName("com.mysql.jdbc.Driver");
String url = "jdbc:mysql://localhost:3306/Crawler";
conn = DriverManager.getConnection(url, "root", "admin213");
System.out.println("conn built");
} catch (SQLException e) {
e.printStackTrace();
} catch (ClassNotFoundException e) {
e.printStackTrace();
}
}
public ResultSet runSql(String sql) throws SQLException {
Statement sta = conn.createStatement();
return sta.executeQuery(sql);
}
public boolean runSql2(String sql) throws SQLException {
Statement sta = conn.createStatement();
return sta.execute(sql);
}
#Override
protected void finalize() throws Throwable {
if (conn != null || !conn.isClosed()) {
conn.close();
}
}
}`
and Main.java:
`import java.io.IOException;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;
import org.jsoup.Jsoup;
import org.jsoup.nodes.Document;
import org.jsoup.nodes.Element;
import org.jsoup.select.Elements;
public class Main {
public static DB db = new DB();
public static void main(String[] args) throws SQLException, IOException {
db.runSql2("TRUNCATE Record;");
processPage("http://www.mit.edu");
}
public static void processPage(String URL) throws SQLException, IOException{
//check if the given URL is already in database
String sql = "select * from Record where URL = '"+URL+"'";
ResultSet rs = db.runSql(sql);
if(rs.next()){
}else{
//store the URL to database to avoid parsing again
sql = "INSERT INTO `Crawler`.`Record` " + "(`URL`) VALUES " + "(?);";
PreparedStatement stmt = db.conn.prepareStatement(sql,
Statement.RETURN_GENERATED_KEYS);
stmt.setString(1, URL);
stmt.execute();
//get useful information
Document doc = Jsoup.connect("http://www.mit.edu/").get();
if(doc.text().contains("research")){
System.out.println(URL);
}
//get all links and recursively call the processPage method
Elements questions = doc.select("a[href]");
for(Element link: questions){
if(link.attr("href").contains("mit.edu"))
processPage(link.attr("abs:href"));
}
}
}
}`
I forgot to include the mysql-connector-java-5.1.16-bin.jar into the buildpath.
This resulted in an exception occuring in the initialization that occurs in the DB()
initializer code. At least this is my assumption that the behaviour of Eclipse was
irritated (maybe it's a feature?) and the step over didn't work right.

Map Reduce Distributed Cache

I am not able to compile my DriverClass at the job.waitforcompletion(boolean) clause.It gives me a NoClassFoundException.If I catch the exception ,the run method throws the error that its expecting a int value.I am using MapReduce New API.Could anyone suggest what is the issue :
import java.io.File;
import java.io.IOException;
import java.net.URI;
import java.net.URISyntaxException;
import org.apache.hadoop.conf.Configuration;
import org.apache.hadoop.conf.Configured;
import org.apache.hadoop.filecache.DistributedCache;
import org.apache.hadoop.fs.Path;
import org.apache.hadoop.util.GenericOptionsParser;
import org.apache.hadoop.util.Tool;
import org.apache.hadoop.util.ToolRunner;
import org.apache.hadoop.mapreduce.Job;
import org.apache.hadoop.mapreduce.lib.input.FileInputFormat;
import org.apache.hadoop.mapreduce.lib.input.KeyValueTextInputFormat;
import org.apache.hadoop.mapreduce.lib.input.TextInputFormat;
import org.apache.hadoop.mapreduce.lib.output.FileOutputFormat;
import org.apache.hadoop.mapreduce.lib.output.TextOutputFormat;
public class Dist_Driver extends Configured implements Tool {
public int run(String args[]) throws IOException, InterruptedException {
// Configuration phase
// Configuration conf=new Configuration();
Job job = new Job(new Configuration());
job.setJarByClass(Dist_Driver.class);
// Mapper Reducer InputFormat
job.setInputFormatClass(FileInputFormat.class);
// Mapper and Reducer Class
job.setMapperClass(Dist_Mapper.class);
job.setReducerClass(DistCache_Reducer.class);
job.setOutputFormatClass(TextOutputFormat.class);
job.setInputFormatClass(KeyValueTextInputFormat.class);
// set FileInputOutput
FileInputFormat.addInputPath(job, new Path(args[0]));
FileOutputFormat.setOutputPath(job, new Path(args[1]));
// setting number of reduce tasks and submit it
job.setNumReduceTasks(2);
// Lets check if the file exist
File f1 = new File("/home/hdfs/trials_mapreduce_progams/emp_id");
if (f1.exists())
System.out.println("The Files Exists");
else
System.out.println("The File doesnot exist");
URI path1;
try {
path1 = new URI(
"/home/hdfs/trials_mapreduce_progams/emp_lookup.txt");
DistributedCache.addCacheFile(path1, job.getConfiguration());
} catch (URISyntaxException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
if (job.waitForCompletion(true))
return 0;
else
return 1;
}
public static void main(String[] args) throws Exception {
int exitcode = ToolRunner.run(new Dist_Driver(), args);
System.exit(exitcode);
}
}
Just add the ClassNotFoundException to the run method signature
public int run(String args[]) throws IOException,
InterruptedException,
ClassNotFoundException {
The reason you get an error when you try and try/catch it is because if there is a ClassNotFoundException thrown during execution, there will be no return value, and the method has to return something.
If you really want to catch it, just return 1 in the catch clause, which is the error exit code

Client IP address using emulator

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();
}
}