I'm having problems when creating a socket in android. I'm using LibGDX.
#Override
public void create() {
System.out.println("Enter IP adress.");
ip = "78.61.65.198";
System.out.println("Connecting...");
socket = connection(PORT, ip);
System.out.println("Setting up InputStream");
reader = reader(socket);
System.out.println("Setting up OutputStream");
output = output(socket);
while (socket.isConnected()) {
output.println("0;" + Gdx.input.getAccelerometerX() + ";" + Gdx.input.getAccelerometerY());
}
}
public static Socket connection(int port, String ip) {
try {
return new Socket(InetAddress.getByName(ip), port);
} catch (UnknownHostException e) {
e.printStackTrace();
System.out.println("Unknown host...");
return null;
} catch (IOException e) {
e.printStackTrace();
System.out.println("Failed to connect...");
return null;
}
}
public static BufferedReader reader(Socket socket) {
try {
return new BufferedReader(new InputStreamReader(socket.getInputStream()));
} catch (IOException e) {
System.err.println("Couldn't get inputStream...");
e.printStackTrace();
return null;
}
}
public static PrintStream output(Socket socket) {
try {
return new PrintStream(socket.getOutputStream());
} catch (IOException e) {
e.printStackTrace();
System.err.println("Couldn't get outputStream");
return null;
}
}
Server:
#Override
public void create() {
System.out.println("Creating server...");
server = hostServer(PORT);
System.out.println("Waiting for Client 1...");
client1 = waitForConnections(server);
System.out.println("Setting up input/output for client 1...");
client1Input = reader(client1);
client1Output = output(client1);
setScreen(new gameScreen(this));
}
public static ServerSocket hostServer(int port){
try {
return new ServerSocket(port);
} catch (IOException e) {
e.printStackTrace();
System.err.println("Failed to host server!");
return null;
}
}
public static BufferedReader reader(Socket socket){
try {
return new BufferedReader(new InputStreamReader(socket.getInputStream()));
} catch (IOException e) {
e.printStackTrace();
System.err.println("Failed to get input stream!");
return null;
}
}
public static PrintStream output(Socket socket){
try {
return new PrintStream(socket.getOutputStream());
} catch (IOException e) {
e.printStackTrace();
System.err.println("Failed to create output stream!");
return null;
}
}
public static Socket waitForConnections(ServerSocket server){
try {
return server.accept();
} catch (IOException e) {
e.printStackTrace();
System.err.println("Failed to accept connection!");
return null;
}
}
It works when i do it with a desktop project, but when i do it with an android project, it doesn't work.
ERROR:
Let me know if anyone has similiar problems or have found a solution.
Assuming both your PC and your Android device are connected to the same LAN (connected to the same router), you should try to use the server's internal IP address (usually looks like: 10.0.0.X or 192.168.X.X), which you can find by running the ipconfig command on the command line in a Windows PC, or ifconfig on Linux/MAC. If your PC and Android device are connected to different networks then you should use the server's external IP address like you did in your example. If it is the latter you should also forward the port your using (1234) to your PC in your router.
When the server is startet on your pc, you cannot connect from another device than your pc as long as you try to connect to localhost/127.0.0.1. Only when running the app on your pc as desktop application the connection will work since client and server are on the same host. For other clients you need to connect to the local LAN IP address of your PC. When you try to connect to localhost/127.0.0.1 from your phone it is looking for a server running on the phone and this is not the case.
Is the client network connection estabished in an UI thread/activity? If so, network connection should established in a separate thread, eg. AsynTask for short operations and services for longer streaming operations. http://developer.android.com/training/basics/network-ops/connecting.html#AsyncTask
Related
A client communicate with authserver to recieve a nickname, and the auhserver send the nickname to clients and another server, in order to client communicate with the other server.
My problem is how to make the other server connect with the client and authserver without making new communication thread for each one?
public class Aatombolaserver extends Thread {
/***in order to differentiate between client socket**/
protected Socket clientSocket;
String serverHostname = new String ("127.0.0.1");
Socket authSocket = null;
/**** constructor**/
private Aatombolaserver (Socket clientSoc)
{clientSocket = clientSoc;
authSocket = clientSoc;
//store the socket of the coming client
start();//execute the run method
}
public static void main(String[] args) throws IOException
{
/**** Create a server socket and wait for a connection**/
ServerSocket serverSocket = null;
// ServerSocket serverSocket1 = null;
try {
serverSocket = new ServerSocket(9091);
// serverSocket1 = new ServerSocket(9092);
System.out.println ("Connection Socket Created");
try { System.out.println ("Waiting for a client to connect");
while (true){//wait for clients
//accept the client request and proceed with the thread creation
new Aatombolaserver(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);
}//end try
/************Close Socket*******************/
finally {
try { serverSocket.close(); }
catch (IOException e){
System.err.println("Could not close port: 10008.");
System.exit(1);
}
}//end finally
}
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();
}
In this site use socket for send message to the server.
I haven't any Error in this project but I doesn't work and don't show nothings in avd, help me to run it. I think the port number or IP number is false and don't know what number is correct.
Did I need to install something?
try this in client.java
class ClientThread implements Runnable {
#Override
public void run() {
try {
socket = new Socket();
InetSocketAddress socketAddress = new InetSocketAddress(SERVER_IP, SERVERPORT);
socket.connect(socketAddress);
} catch (UnknownHostException e1) {
e1.printStackTrace();
}catch (IOException e1) {
e1.printStackTrace();
}
}
}
This may be a stupid question, but here goes.
Im writing this chat program, where there is a server, and clients that can connect to it. I want to implement private messaging into the program, but I don't know how to get the clients to directly connect to eachother. For the server, I used a ServerSocket, which runs on a single port. To get that to work, I needed to forward a port to the server. Is there a way to get the clients to wait for connections, without forwarding a port to them?
Thanks
The whole point of TCP/IP is that a single client connects to a predefined port on a server. So yes, you'll also need to have a ServerSocket on the client that's going to accept the direct connection. You'll almost always run into trouble with port forwarding and the like, which is why UPnP was invented one day.
What you are trying to do is 'peer to peer' connectivity, aka P2P, which is always, by its very definition, plagued by firewalling problems. As such it's usually, especially for a chat, easier to use the central server as 'switchboard' server and relay the private messages as well.
I've written not long time ago a template for multiple client - server application, that might help you to solve your problem. The rest of your question was already answerd by #Niels, I think ;)
import java.net.*;
import java.io.*;
class ServeConnection extends Thread {
private Socket socket = null;
private BufferedReader in = null;
private PrintWriter out = null;
public ServeConnection(Socket s) throws IOException {
// init connection with client
socket = s;
try {
in = new BufferedReader(new InputStreamReader(
this.socket.getInputStream()));
out = new PrintWriter(this.socket.getOutputStream(), true);
} catch (IOException e) {
System.err.println("Couldn't get I/O.");
System.exit(1);
}
start();
}
public void run() {
System.out.println("client accepted from: " + socket.getInetAddress()
+ ":" + socket.getPort());
// get commands from client, until is he communicating or until no error
// occurs
String inputLine, outputLine;
try {
while ((inputLine = in.readLine()) != null) {
System.out.println("request: " + inputLine);
outputLine = inputLine;
out.println("I've recived "+outputLine);
} catch (IOException e) {
e.printStackTrace();
}
System.out.println("server ending");
out.close();
try {
in.close();
socket.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
class Server {
public static void svr_main(int port) throws IOException {
ServerSocket serverSocket = null;
try {
serverSocket = new ServerSocket(port);
} catch (IOException e) {
System.err.println("Could not listen on port: " + port);
System.exit(1);
}
System.out.println("Server ready");
try {
while (true) {
Socket socket = serverSocket.accept();
try {
new ServeConnection(socket);
} catch (IOException e) {
System.err.println("IO Exception");
}
}
} finally {
serverSocket.close();
}
}
}
class Client {
static Socket echoSocket = null;
static PrintWriter out = null;
static BufferedReader in = null;
public static void cli_main(int port, String servername) throws
IOException {
try {
echoSocket = new Socket(servername, port);
out = new PrintWriter(echoSocket.getOutputStream(), true);
in = new BufferedReader(new InputStreamReader(
echoSocket.getInputStream()));
} catch (UnknownHostException e) {
System.err.println("Don't know about host: " + servername);
System.exit(1);
} catch (IOException e) {
System.err.println("Couldn't get I/O for " + servername);
System.exit(1);
}
System.out.println("Client ready!");
while (true) {
inputLine = (in.readLine().toString());
if (inputLine == null) {
System.out.println("Client closing!");
break;
}
// get the input and tokenize it
String[] tokens = inputLine.split(" ");
}
out.close();
in.close();
echoSocket.close();
System.out.println("Client closing");
}
}
public class MyClientServerSnippet{
public static void main(String[] args) throws IOException {
if (args.length == 0) {
System.err.println("Client: java snippet.MyClientServerSnippet<hostname> <port>");
System.err.println("Server: java snippet.MyClientServerSnippet<port>");
System.exit(1);
}
else if (args.length > 1) {
System.out.println("Starting client...\n");
Client client = new Client();
client.cli_main(3049, "127.0.0.1");
} else {
System.out.println("Starting server...\n");
Server server = new Server();
server.svr_main(3049);
}
}
}
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.