Socket Crashes Thread - java

Problem:
My #Override run() method which is part of the class that implements Runnable, is called constantly like normal. However, the moment I open up a socket connection, that thread seems to stop, without throwing any errors. If I connect the client to a server socket, it works just fine, however the GUI which is being ticked by the #Override run() method just stops working
Run Method:
#Override
public void run()
{
}
Server Socket (which stops the run() method from being invoked):
public class CommonProxy
{
public static boolean isActive = false;
public static void startServer() throws IOException
{
isActive = true;
Socket socket;
OutputStreamWriter outputStreamWriter;
InputStreamReader inputStreamReader;
BufferedWriter bufferedWriter;
BufferedReader bufferedReader;
ServerSocket serverSocket;
serverSocket = new ServerSocket(1234);
while (isActive)
{
try
{
socket = serverSocket.accept();
System.out.println("hi");
outputStreamWriter = new OutputStreamWriter(socket.getOutputStream());
inputStreamReader = new InputStreamReader(socket.getInputStream());
bufferedWriter = new BufferedWriter(outputStreamWriter);
bufferedReader = new BufferedReader(inputStreamReader);
while (isActive)
{
String clientMessage = bufferedReader.readLine();
System.out.println("[Client]: " + clientMessage);
bufferedWriter.write("Message Recieved");
bufferedWriter.newLine();
bufferedWriter.flush();
if (clientMessage.equalsIgnoreCase("exit"))
{
System.out.println("Client Disconnected");
break;
}
}
socket.close();
inputStreamReader.close();
outputStreamWriter.close();
bufferedReader.close();
bufferedWriter.close();
} catch (IOException e)
{
e.printStackTrace();
}
}
}
}
Client socket (which also stops the method from being invokes) if needed:
public static void startClient(String address, int port)
{
isActive = true;
Socket socket = null;
OutputStreamWriter outputStreamWriter = null;
InputStreamReader inputStreamReader = null;
BufferedWriter bufferedWriter = null;
BufferedReader bufferedReader = null;
try
{
socket = new Socket("192.168.0.100", 1234);
System.out.println(socket.getLocalAddress().getHostAddress());
outputStreamWriter = new OutputStreamWriter(socket.getOutputStream());
inputStreamReader = new InputStreamReader(socket.getInputStream());
bufferedWriter = new BufferedWriter(outputStreamWriter);
bufferedReader = new BufferedReader(inputStreamReader);
Scanner scanner = new Scanner(System.in);
while (isActive)
{
String queuedMessage = scanner.nextLine();
bufferedWriter.write(queuedMessage);
bufferedWriter.newLine();
bufferedWriter.flush();
System.out.println(bufferedReader.readLine());
if (queuedMessage.equalsIgnoreCase("exit"))
break;
}
}
catch(IOException e)
{
e.printStackTrace();
}
finally
{
try
{
if (socket != null) socket.close();
if (inputStreamReader != null) inputStreamReader.close();
if (outputStreamWriter != null) outputStreamWriter.close();
if (bufferedReader != null) bufferedReader.close();
if (bufferedWriter != null) bufferedWriter.close();
}
catch (IOException e)
{
e.printStackTrace();
}
}
}
public static void queueMessage(String message)
{
queuedMessage = message;
}
public static String getMessage()
{
return lastServerMessage;
}

Related

Android Client Socket IOException

EDIT: The problem is the input in the Client.class so when the Android devices receives an answer from the Server. Those are the following lines that causes the crash:
InputStream input = client.getInputStream();
BufferedReader reader = new BufferedReader(new InputStreamReader(input));
String text;
while ((text = reader.readLine()) != null) {
Log.d("ClientLog", "Received from Server"+ text);
}
Here is my Client.class in Android:
public class Client implements Runnable{
public Client() {
}
#Override
public void run() {
try {
Log.d("ClientLog", "Socket creation incoming");
Socket client = new Socket("localhost", 5555);
Log.d("ClientLog", "Client has been started");
// Streams:
OutputStream out = client.getOutputStream();
BufferedWriter writer = new BufferedWriter(new OutputStreamWriter(client.getOutputStream()));
InputStream input = client.getInputStream();
BufferedReader reader = new BufferedReader(new InputStreamReader(input));
// -----------------------------------------------------------------------
writer.write("Test");
writer.newLine();
writer.flush();
String text;
while ((text = reader.readLine()) != null) {
Log.d("ClientLog", "Received from Server"+ text);
}
writer.close();
reader.close();
} catch (UnknownHostException e) {
Log.d("ClientLog", "Error: Host not found");
e.printStackTrace();
} catch (IOException e) {
Log.d("ClientLog", "Error: IOException");
e.printStackTrace();
}
}
}
And if needed my Server.class in Java:
public class Server {
public static void main(String[] args) {
ExecutorService executor = Executors.newFixedThreadPool(30);
ServerSocket server;
try {
server = new ServerSocket(5555);
System.out.println("Server has been started on Port 5555");
while(true) {
try {
Socket client = server.accept();
//Thread t = new Thread(new Handler(client));
//t.start();
executor.execute(new Handler(client));
} catch (IOException e) {
System.out.println("Error IOExceotion");
e.printStackTrace();
}
}
} catch (IOException e1) {
e1.printStackTrace();
}
}
The Handler.class needed for Server.class:
public class Handler implements Runnable{
private Socket client;
public Handler(Socket pClient) {
client = pClient;
}
#Override
public void run() {
try {
// Streams:
OutputStream out = client.getOutputStream();
PrintWriter writer = new PrintWriter(out);
InputStream input = client.getInputStream();
BufferedReader reader = new BufferedReader(new InputStreamReader(input));
// -----------------------------------------------------------------------
String text = null;
while ((text = reader.readLine()) != null) {
writer.write(text+ "\n");
writer.flush();
System.out.println("Recieved from Client: "+ text);
}
//Close Streams
writer.close();
reader.close();
client.close();
} catch (IOException e) {
System.out.println("Error IOException");
e.printStackTrace();
}
}
}
The debugging was resolved in the comments above.
Step 1: Add permissions to the android manifest file as was outlined here: Java socket IOException - permission denied
Step 2: Change the while ((text = reader.readLine()) != null) check. I guess the text = reader.readLine() != null check was problematic.

Access class or singleton from other activities

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) { }
}
}

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

How can I transfer files from Server-Side to Client using Sockets?

I'm having trouble on where to begin performing this task, I'd like some examples or input on how I should set up my server/client components to receive and send data including letting the client download images.
Here's my client-side code:
package V3;
import java.io.*;
import java.net.*;
public class Version3Client {
public static void main(String[] args) throws IOException {
Socket kkSocket = null;
PrintWriter out = null;
BufferedReader in = null;
try {
kkSocket = new Socket("localhost", 4444);
out = new PrintWriter(kkSocket.getOutputStream(), true);
in = new BufferedReader(new InputStreamReader(kkSocket.getInputStream()));
} catch (UnknownHostException e) {
System.err.println("Don't know about host: taranis.");
System.exit(1);
} catch (IOException e) {
System.err.println("Couldn't get I/O for the connection to: taranis.");
System.exit(1);
}
BufferedReader stdIn = new BufferedReader(new InputStreamReader(System.in));
String fromServer;
String fromUser;
while ((fromServer = in.readLine()) != null) {
System.out.println("Server: " + fromServer);
if (fromServer.equals("Bye."))
break;
fromUser = stdIn.readLine();
if (fromUser != null) {
System.out.println("Client: " + fromUser);
out.println(fromUser);
}
}
out.close();
in.close();
stdIn.close();
kkSocket.close();
}
}
And here's my server-side code:
package V3;
import java.net.*;
import java.io.*;
public class Version3Server {
public static void main(String[] args) throws IOException {
ServerSocket serverSocket = null;
boolean listening = true;
try {
serverSocket = new ServerSocket(4444);
} catch (IOException e) {
System.err.println("Could not listen on port: 4444.");
System.exit(-1);
}
while (listening)
new Version3ServerThread(serverSocket.accept()).start();
serverSocket.close();
Socket clientSocket = null;
try {
clientSocket = serverSocket.accept();
} catch (IOException e) {
System.err.println("Accept failed.");
System.exit(1);
}
PrintWriter out = new PrintWriter(clientSocket.getOutputStream(), true);
BufferedReader in = new BufferedReader(
new InputStreamReader(
clientSocket.getInputStream()));
String inputLine, outputLine;
Version3Protocol kkp = new Version3Protocol();
outputLine = kkp.processInput(null);
out.println(outputLine);
while ((inputLine = in.readLine()) != null) {
outputLine = kkp.processInput(inputLine);
out.println(outputLine);
if (outputLine.equals("Bye."))
break;
}
out.close();
in.close();
clientSocket.close();
serverSocket.close();
}
}
Thread class added for further specification:
package V3;
import java.net.*;
import java.io.*;
import java.io.FileWriter;
public class Version3ServerThread extends Thread {
private Socket socket = null;
public Version3ServerThread(Socket socket) {
super("Version3ServerThread");
this.socket = socket;
}
public void run() {
try {
PrintWriter out = new PrintWriter(socket.getOutputStream(), true);
BufferedReader in = new BufferedReader(
new InputStreamReader(
socket.getInputStream()));
String inputLine, outputLine;
Version3Protocol kkp = new Version3Protocol();
outputLine = kkp.processInput(null);
out.println(outputLine);
while ((inputLine = in.readLine()) != null) {
outputLine = kkp.processInput(inputLine);
out.println(outputLine);
if (outputLine.equals("Bye"))
break;
if(kkp.getInteraction()){
Logging.writeToFile(socket.getInetAddress());
}
}
out.close();
in.close();
socket.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
The code so far, the client-server-communication without the file-transfer ability, looks fine to me. I wanted to compile to find any errors but you didnt include Version3Protocol and Logging. If it does compile then your next step would be to open the file you want to transfer on the server with a FileInputStream and a new file for writing on the client with FileOutputStream:
http://download.oracle.com/javase/1.4.2/docs/api/java/io/FileInputStream.html
http://download.oracle.com/javase/1.4.2/docs/api/java/io/FileOutputStream.html
You can then read the file into buffer, transfer it using the socket, receive it on the client-side, and copy the buffer-contents into the FileOutputStream there.

Categories