Access class or singleton from other activities - java

So I have network socket class that should be handling my socket connection that i want running when my app is running. Problem is I dont know how to reference the class other than just starting a new one.
To start a new one I would do:
Networker network = null;
try {
network = new Networker(SERVER_IP, SERVERPORT);
new Thread(network).start();
Then i could do:(from the same activity I just did the above in)
network.send("helloworld");
How can i do a network.send in any class without making a whole new socket connection?
Edit:
Here is my Networker Class:
public class Networker implements Runnable, Closeable {
private final Socket clientSocket;
private final PrintWriter out;
private final BufferedReader in;
private volatile boolean closed = false;
public Networker(String hostname, int port) throws IOException {
clientSocket = new Socket(hostname, port);
out = new PrintWriter(clientSocket.getOutputStream(), true);
in = new BufferedReader(new InputStreamReader(clientSocket.getInputStream()));
}
public void run() {
try {
for(String fromServer; (fromServer = in.readLine()) != null;)
System.out.println("Server: " + fromServer);
} catch (IOException ex) {
if (!closed)
Log.i("logging", "error") ;
}
}
public void send(String line) {
out.println(line);
}
public void close() {
closed = true;
try { clientSocket.close(); } catch (IOException ignored) { }
}
}

Related

Can send but cannot receive data through socket in my service [duplicate]

This question already has answers here:
Java Socket why server can not reply client
(4 answers)
Closed 3 years ago.
My android app is supposed to send data to the server through socket but also occasionally receive data from that server. To do that I am using service and.
Sending data to the server works ok, I'm using service method that i'm calling from activity. But while sending works just fine my app doesnt receive any data back. While I send string "pp" I should get another sring back from server but that just doesn't happen. What am I doing wrong?
My service:
public class MyService extends Service {
private Socket socket;
public static PrintWriter out;
private BufferedReader in;
private String line;
private final IBinder binder = new MyBinder();
#Nullable
#Override
public IBinder onBind(Intent intent) {
return binder;
}
public class MyBinder extends Binder {
MyService getMyService() {
return MyService.this;
}
}
#Override
public int onStartCommand(Intent intent, int flags, int startId) {
new Thread(new Runnable() {
public void run() {
try {
InetAddress serverAddr = InetAddress.getByName("10.0.2.2");
socket = new Socket(serverAddr,8998);
out = new PrintWriter(new BufferedWriter(new OutputStreamWriter(socket
.getOutputStream())), true);
in = new BufferedReader(new InputStreamReader(socket.getInputStream()));
Thread thread = new Thread(new Listener());
thread.start();
} catch (IOException e) {
e.printStackTrace();
}
}
}).start();
return START_STICKY;
}
private class Listener implements Runnable{
#Override
public void run() {
while(true){
try {
line = in.readLine();
if(line!=null) Log.d(line,line); //never shows up in logcat
line=null;
}
catch (Exception e) {
e.printStackTrace();
}
}
}
}
public void send(String line){
out.println(line);
}
}
And my server:
public class Server {
private static final int SERVER_PORT = 8998;
private static ServerSocket server = null;
private static Socket client = null;
private static BufferedReader in = null;
private static boolean isConnected = true;
private static String line;
public static void main(String[] args){
while(isConnected){
if(server==null || server.isClosed()){
try{
server = new ServerSocket(SERVER_PORT);
client = server.accept();
in = new BufferedReader(new InputStreamReader(client.getInputStream()));
System.out.println("Connected");
}catch (IOException e){
System.out.println("Error in opening Socket"+e);
System.exit(-1);
}
}
else{
try{
line = in.readLine();
if(line != null)
{
if(line.equals("pp")){
PrintWriter out = new PrintWriter(new BufferedWriter(
new OutputStreamWriter(client.getOutputStream())),
true);
String toSend = "String to send";
out.write(toSend);
System.out.println("sent");
}
System.out.println(line);
}else if(in.read()==-1){
client.close();
server.close();
}
}catch (IOException e){
System.out.println("Read from client failed");
System.exit(-1);
}
}
}
}
}
Usual problems.
You are reading lines but you aren't writing lives. Add a line terminator.
You should stop reading when readLine() returns null, and close the socket.
Once readLine() has returned null, the extra read test is pointless. It will always return -1.

How to enable multiple clients to communicate with the server?

The problem am having is that am not sure how to enable multiple clients to communicate with the server through threading, i've attempted it but I think am doing something wrong. Any help will be appreciated.
import java.io.*;
import java.net.*;
import java.util.*;
public class ChatServer {
ArrayList clientOutputStreams;
public class ClientHandler implements Runnable {
BufferedReader reader;
Socket sock;
public ClientHandler(Socket clientSocket) {
try {
sock = clientSocket;
InputStreamReader isReader = new InputStreamReader(
sock.getInputStream());
reader = new BufferedReader(isReader);
} catch (Exception x) {
}
}
public void run() {
String message;
try {
while ((message = reader.readLine()) != null) {
System.out.println("read" + message);
tellEveryone(message);
}
} catch (Exception x) {
}
}
}
public void go() {
clientOutputStreams = new ArrayList();
try {
ServerSocket serverSock = new ServerSocket(5000);
while (true) {
Socket clientSocket = serverSock.accept();
PrintWriter writer = new PrintWriter(
clientSocket.getOutputStream());
clientOutputStreams.add(writer);
Thread t = new Thread(new ClientHandler(clientSocket));
t.start();
System.out.println("got a connection");
}
} catch (Exception x) {
}
}
public void tellEveryone(String message) {
Iterator it = clientOutputStreams.iterator();
while (it.hasNext()) {
try {
PrintWriter writer = (PrintWriter) it.next();
writer.println(message);
writer.flush();
} catch (Exception x) {
}
}
}
public static void main(String[] args) {
new ChatServer().go();
}`enter code here`
}
To allow multiple client to connect to your server you need a server to be continually looking for a new client to connect to. This can be done like:
while(true) {
Socket socket = Ssocket.accept();
[YourSocketClass] connection = new [YourSocketClass](socket);
Thread thread = new Thread(connection);
thread.start();
}
This is probably also best done in a separate server java file that can run independent of the client.

Handle more clients

Right now my server only can handle one client at a time. I am trying to use a Thread so that the server can handle several clients, but I am doing it wrong. I have added the thread in the try/catch clause where the serverSocket accepts the client, but this makes no difference. I don't get an error or anything, but it just doesn't work.
So what I want to do, is make the server not freeze at one client, but still accept several clients.
Here is the server code:
import java.io.*;
import java.net.*;
public class Server {
private BufferedReader reader;
private PrintWriter writer;
private int port;
public Server(int port)
{
this.port = port;
}
private String getSeverAddress() {
String host = null;
try {
InetAddress adr = InetAddress.getLocalHost();
host = adr.getHostAddress();
} catch (UnknownHostException e) {
e.printStackTrace();
}
return host;
}
public void startServer() {
print("Contact this sever on address: " + getSeverAddress() + " port: " + port);
ServerSocket ss = null;
Socket socket = null;
Thread clientThread = null;
try {
ss = new ServerSocket(port);
socket = ss.accept();
clientThread = new Thread(new Client(socket));
clientThread.start();
reader = new BufferedReader(new InputStreamReader(socket.getInputStream()));
writer = new PrintWriter(socket.getOutputStream(), true);
String msg = null;
while (( msg = reader.readLine()) != null) {
print("System out: " + msg);
if(msg.equals("Bye")) {
print("Client left");
break;
}
}
ss.close();
socket.close();
reader.close();
writer.close();
} catch(SocketException e) {
e.printStackTrace();
} catch (IOException i ) {
i.printStackTrace();
return;
}
}
private void print(String msg) {
System.out.println(msg);
}
public static void main(String[] args) {
Server server = new Server(1111);
server.startServer();
}
}
Here is the client code:
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.PrintWriter;
import java.net.Socket;
public class Client implements Runnable{
private Socket client;
private BufferedReader reader;
private PrintWriter writer;
public Client(Socket socket)
{
client = socket;
try{
reader = new BufferedReader(new InputStreamReader(client.getInputStream()));
writer = new PrintWriter(client.getOutputStream(), true);
} catch (Exception e) {
e.printStackTrace();
return;
}
}
#Override
public void run() {
String msg = null;
BufferedReader r = null;
try {
r = new BufferedReader(new InputStreamReader(System.in));
} catch (Exception e1) {
e1.printStackTrace();
}
System.out.println("Write message to server");
while(true) {
try {
msg = r.readLine();
if(msg.equals("Quit") || msg == null) {
print("Disconnect");
break;
}
} catch (IOException e) {
e.printStackTrace();
}
writeToServer(msg);
}
try {
r.close();
} catch (IOException e) {
e.printStackTrace();
}
}
public void writeToServer(String msg) {
writer.println(msg);
}
private void print(String msg) {
System.out.println(msg);
}
public static void main(String[] args) {
Socket socket = null;
try {
socket = new Socket("localhost", 1111);
} catch (Exception e) {
e.printStackTrace();
}
Client client = new Client(socket);
client.run();
}
}
You are still trying to handle clients in your main thread. Main thread should just accept new connections and start new threads. You also have to do accept in a loop so multiple connections can be accepted:
ss = new ServerSocket(port);
while(true) {
Socket socket = ss.accept();
Thread clientThread = new Thread(new Runnable() {
public void run() {
BufferedReader reader = new BufferedReader(new InputStreamReader(socket.getInputStream()));
PrintWriter writer = new PrintWriter(socket.getOutputStream(), true);
String msg = null;
while (( msg = reader.readLine()) != null) {
print("System out: " + msg);
if(msg.equals("Bye")) {
print("Client left");
break;
}
}
socket.close();
reader.close();
writer.close();
}});
clientThread.start();
}
You need to put your ss.accept() into a while loop and create a new Thread for every client accepted, which handles the connection.

Java Socket Programing

Problem:
I have written one java socket server which send response when I send first message from the client to it. But I want to send one more message based on the first response. After the first response i am not getting any other response?
Here is the Server code:
public class SendSmsServerSocket {
private final static CxpsLogger logger = CxpsLogger.getLogger(SendSmsServerSocket.class);
SendSmsServerSocket(){
try {
new SeverSocketForSms(new ServerSocket(4330));
} catch (IOException e) {
e.printStackTrace();
}
}
}
private static class SeverSocketForSms extends Thread {
private Socket socket;
private ServerSocket serversocket;
private volatile static boolean running = true;
public SeverSocketForSms(ServerSocket ssocket) throws IOException {
this.serversocket = ssocket;
start();
}
public void run() {
try{
while(running) {
this.socket = serversocket.accept();
InputStreamReader ir = new InputStreamReader(socket.getInputStream());
BufferedReader br = new BufferedReader(ir);
String msg = br.readLine();
PrintStream ps = new PrintStream(socket.getOutputStream());
ps.println("inside SeverSocketForSms: msg received is : "+msg);
}
}
catch(Exception e){
e.printStackTrace();
}
catch(Throwable t) {
System.out.println("Caught " + t + "xmlServerThread - closing thread");
}
}
public static void shutdown() {
System.out.println("Stopping socket connection and thread");
try{
socket.close();
}catch (Exception e) {
e.printStackTrace();
}
running = false;
}
public static void main (String [] args){
try {
System.out.println("Starting sms server ----- Please press Enter Key to stop the server after receiving one message");
SendSmsServerSocket s=new SendSmsServerSocket();
new Scanner(System.in).nextLine();
SeverSocketForSms.shutdown();
} catch (Exception e) {
e.printStackTrace();
}
}
}
Once you have an incoming connection, you should delgate the responsibility for handling that incoming connection to another Thread, otherwise you will block your "accept" thread until the current connection is closed...
while (running) {
this.socket = serversocket.accept();
Thread thread = new Thread(new Handler(socket));
thread.start();
}
And the Handler
public class Handler implements Runnable {
private Socket socket;
public Handler(Socket socket){
this.socket = socket;
}
public void run() {
// You may need to add a repeat and exit clause here...
InputStreamReader ir = new InputStreamReader(socket.getInputStream());
BufferedReader br = new BufferedReader(ir);
String msg = br.readLine();
PrintStream ps = new PrintStream(socket.getOutputStream());
ps.println("inside SeverSocketForSms: msg received is : " + msg);
}
}

Java Server And Client Socket Need Fix

Hello, I am new to java socket programming and I was just looking to see if somebody could give me some help.
I will post the code for the client and server then i will explain my problem...
reader = new BufferedReader(new InputStreamReader(socket.getInputStream));
while(running)
{
String line = reader.readLine();
if(line != null)
{
System.out.println(line);
stream = new PrintStream(socket.getOutputStream());
stream.println("return: " + line);
}
}
}catch(IOException e)
{
System.out.println("Socket in use or not available: " + port);
}
}
public static void main()
{
run();
}
//Client
public static String ip;
public static int port;
public static Socket socket;
public static PrintStream stream;
public static BufferedReader reader;
public static void main(String args[])
{
try
{
socket = new socket(ip, port);
stream = new PrintStream(socket.getOutputStream());
stream.println("test0");
reader = new BufferedReader(new InputStreamReader(socket.getInputStream));
String line = reader.readLine();
if(line != null)
{
System.out.println(line);
}
stream.println("test1");
line = reader.readLine();
if(line != null)
{
System.out.println(line);
}
}catch(IOException e)
{
System.out.println("could not connect to server!");
}
}
So my problem is even if I get rid of the loop and try to make it send the string twice it won't send it. It will only do it once unless I close and make a new socket on the client side. So if anybody could give me an explanation to what I am doing wrong that would be great, and thank you so much.
Why are you openning your outstream inside your loop?
stream = new PrintStream(socket.getOutputStream());
Take this statement outside the loop and write to your stream inside your loop.
Please keep it simple,
Try using InputStream, InputStreamReader, BufferedReader, OutputStream, PrintWriter.
Client Side:
Socket s = new Socket();
s.connect(new InetSocketAddress("Server_IP",Port_no),TimeOut);
// Let Timeout be 5000
Server Side:
ServerSocket ss = new ServerSocket(Port_no);
Socket incoming = ss.accept();
For Reading from the Socket:
InputStream is = s.getInputStream();
InputStreamReader isr = new InputStreamReader(is);
BufferedReader br = new BufferedReader(isr);
boolean isDone = false;
String s = new String();
while(!isDone && ((s=br.readLine())!=null)){
System.out.println(s); // Printing on Console
}
For Writing to the Socket:
OutputStream os = s.getOuptStream();
PrintWriter pw = new PrintWriter(os)
pw.println("Hello");
Make sure you flush the output from your server:
stream.flush();
Thanks a lot to everybody who answered but i figures out what it was all along.
i read through some of the Oracle socket stuff and figured out that the server was supposed to be the first to send a message than the client receive and send and receive... so on and so forth so i will post my new code here in hopes somebody else trying to figure out the same thing can find it with ease
//Client
public static String ip;
public static int port;
public static Socket socket;
public static PrintWriter print;
public static BufferedReader reader;
public Client(String ip, int port)
{
this.ip = ip;
this.port = port;
//initiate all of objects
try
{
socket = new Socket();
socket.connect(new InetSocketAddress(ip, port), 5000);
print = new PrintWriter(socket.getOutputStream());
reader = new BufferedReader(new InputStreamReader(socket.getInputStream()));
//start connection with server
String line = reader.readLine();
System.out.println(line);
} catch (IOException e)
{
e.printStackTrace();
}
}
//quick method to send message
public void sendMessage(String text)
{
print.println(text);
print.flush();
try
{
String line = reader.readLine();
System.out.println(line);
} catch (IOException e)
{
e.printStackTrace();
}
}
}
public static void main(String args[])
{
client.sendMessage("test");
client.sendMessage("test2");
client.sendMessage("test3")
}
//Server
public static int port = 9884;
public static boolean running = true;
public static ServerSocket serverSocket;
public static Socket socket;
public static PrintWriter writer;
public static BufferedReader reader;
public static void run()
{
try
{
serverSocket = new ServerSocket(port);
socket = serverSocket.accept();
writer = new PrintWriter(socket.getOutputStream(), true);
writer.println("connection");
while(running)
{
reader = new BufferedReader(new InputStreamReader(socket.getInputStream()));
String line = reader.readLine();
if(line != null)
{
System.out.println(line);
writer.println(line);
writer.flush();
}
}
} catch (IOException e)
{
e.printStackTrace();
}
}
public static void main(String args[])
{
run();
}

Categories