I'm trying to send a string from my java server to an android client over a socket. Instead of showing the correct String which would be "OK" the read method of the InputStreamReader returns
"��OK".
The code of the server looks like this:
public void run() {
try {
DataOutputStream dOut = new DataOutputStream(socket.getOutputStream());
dOut.writeUTF("OK");
dOut.flush();
dOut.close();
socket.close();
System.out.println("Disconnected from client number: " + id);
} catch (IOException ex) {
Logger.getLogger(ThreadImpl.class.getName()).log(Level.SEVERE, null, ex);
}
}
And the code of the client looks like this:
public void run() {
try {
Socket socket = null;
try {
socket = new Socket("10.0.2.2", 1978);
} catch (IOException e) {
e.printStackTrace();
}
String serverRes = null;
BufferedReader reader = new BufferedReader(new InputStreamReader(socket.getInputStream()));
ServerRes = reader.readLine();
System.out.println(ServerRes);
reader.close();
socket.close();
} catch (Exception e) {
e.printStackTrace();
}
}
You should be using a DataInputStream instead of an InputStreamReader. This is the source of your problem
InputStreamReader reader = new DataInputStream(socket.getInputStream()));
String inStr = reader.readUTF();
Related
My server is not sending a response with BufferedWriter out to the client. It seems as if the code stops at int amountOfNumbersToBeGenerated = Integer.parseInt(bufferedReader.readLine()); I believe the bufferedreader.readline() call on the client side is causing and issue and blocking the connection in some sense.
import java.io.*;
import java.net.Socket;
import java.util.ArrayList;
public class ThreadedConnection implements Runnable {
private Socket connection;
private InputStream in;
private OutputStream out;
public ThreadedConnection(Socket connection) {
this.connection = connection;
try {
this.in = this.connection.getInputStream();
this.out = this.connection.getOutputStream();
} catch (IOException e) {
e.printStackTrace();
}
}
#Override
public void run() {
BufferedReader bufferedReader = new BufferedReader(new InputStreamReader(in));
BufferedWriter bufferedWriter = new BufferedWriter(new OutputStreamWriter(out));
try {
String lotteryType = bufferedReader.readLine(); //reads first line of input stream
int amountOfNumbersToBeGenerated = Integer.parseInt(bufferedReader.readLine());
System.out.println("3"+amountOfNumbersToBeGenerated);
switch (lotteryType) {
case "LuckyForLife":
generateLotteryNumbers(amountOfNumbersToBeGenerated, 48, 18, bufferedWriter);
break;
case "MegaMillions":
generateLotteryNumbers(amountOfNumbersToBeGenerated, 70, 25, bufferedWriter);
break;
case "PowerBall":
generateLotteryNumbers(amountOfNumbersToBeGenerated, 69, 26, bufferedWriter);
break;
default:
break;
}
bufferedWriter.flush();
} catch (IOException e) {
e.printStackTrace();
}finally {
try {
connection.close();
bufferedReader.close();
bufferedWriter.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
public void generateLotteryNumbers(int amountOfNumbersToBeGenerated, int upperLimitOfGeneratedNumbers, int upperLimitOfExtraNumber, BufferedWriter bufferedWriter){
RandomNumberGenerator randomNumbers = new RandomNumberGenerator(amountOfNumbersToBeGenerated,upperLimitOfGeneratedNumbers);
RandomNumberGenerator extraNumber = new RandomNumberGenerator(1,upperLimitOfExtraNumber);
ArrayList randomNumbersArrayList = randomNumbers.NumberGenerator();
ArrayList extraNumberArrayList = extraNumber.NumberGenerator();
String randomNumbersString = randomNumbersArrayList.toString();
randomNumbersString = randomNumbersString.substring(1, randomNumbersString.length()-1);
String extraNumberString = extraNumberArrayList.toString();
extraNumberString = extraNumberString.substring(1, extraNumberString.length()-1);
try {
bufferedWriter.write(randomNumbersString);
bufferedWriter.newLine();
bufferedWriter.write(extraNumberString);
bufferedWriter.newLine();
bufferedWriter.flush();
} catch (IOException e) {
e.printStackTrace();
}
// System.out.println(randomNumbersString);
// System.out.println(extraNumberString);
}
}
Here is the code for the client side. I think the first String gerneretedNumber = bufferedReader.readLine(); is causing the issue. Almost as if it is called to read when there is nothing being written out from the server and then messing with the server side read. If I block both of the readline() calls the code on the server then works and I can get something to print out on console.
static void runClient(){
OutputStream outputStream;
InputStream inputStream;
Socket client;
BufferedWriter bufferedWriter;
BufferedReader bufferedReader;
try {
System.out.println("Creating client socket ");
client = new Socket("127.0.0.1", 5000);
outputStream = client.getOutputStream();
inputStream = client.getInputStream();
bufferedWriter = new BufferedWriter(new
OutputStreamWriter(outputStream));
//bufferedReader = new BufferedReader(new
InputStreamReader(System.in));
bufferedReader = new BufferedReader(new
InputStreamReader(inputStream));
bufferedWriter.write("LuckyForLife");
bufferedWriter.newLine();
bufferedWriter.write("5");
bufferedWriter.flush();
String generetedNumber = bufferedReader.readLine();
String extraNumber = bufferedReader.readLine();
System.out.println(gerneretedNumber);
System.out.println(extraNumber);
System.out.println("Guess its null");
bufferedReader.close();
bufferedWriter.close();
client.close();
} catch (UnknownHostException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
}
If anymore information is needed I am happy to post it.
your client never sends the 2nd newline.
Given your protocol, client doesn't half close (output close) so the server cannot either detect end of stream.
BTW, try to close streams (tcp FIN) before close socket (tcp RST); it's more "ethical" ! Kidding aside, the tcp rst is a kill, and pending bytes might not be flushed out (although you have plenty of flushes here, it's just good practice).
I want to have a Server that is running and receives messages from Clients such as another Java Applications. I am doing this via BufferedReader with an InputStream and as long as i do it a single time it works as expected. The message gets processed by the method and writes the Test Message of the received message on the screen, but if i let it run in a while loop it says -
java.net.SocketException: Connection reset
So once the Server got a message i dont know how to get a second one, or any following one.
My main source code is:
public static void main (String[] args) {
int port = 13337;
BufferedReader msgFromClient = null;
PrintWriter msgToClient = null;
timeDate td = new timeDate(); //Class i did for myself to get time/date
ServerSocket s_socket = null;
try {
s_socket = new ServerSocket(port);
System.out.println("Server startet at "+td.getCurrDate()+" "+td.getCurrTime());
}
catch (IOException ioe) {
System.out.println("Server on Port "+port+" couldnt be created. \nException: "+ioe.getMessage());
}
Socket socket = null;
try {
socket = s_socket.accept();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
try {
msgFromClient = utils.createInputStream(socket);
} catch (IOException ioe) {
System.out.println("Creation of an Input Stream failed.\n Exception - "+ioe);
}
try {
msgToClient = utils.createOutputStream(socket);
} catch (IOException ioe) {
System.out.println("Creation of an Output Stream failed.\n Exception - "+ioe);
}
String input = null;
while (true) {
try {
input = msgFromClient.readLine();
} catch (IOException ioe) {
System.out.println(ioe);
}
if(input!=null) {
System.out.println("Jumping out of loop: "+input);
utils.processCode(input);
}
}
The both classes to create the streams look like this:
public static BufferedReader createInputStream (Socket socket) throws IOException {
BufferedReader br = new BufferedReader(new InputStreamReader(socket.getInputStream()));
return br;
}
public static PrintWriter createOutputStream (Socket socket) throws IOException {
PrintWriter pw = new PrintWriter(socket.getOutputStream(), true);
return pw;
}
The "processCode" class then simply is a switch.
Socket socket = null;
try {
socket = s_socket.accept();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
You only accept one Connection an after this you are doing your handling. You need to open an new Thread for every connection
ExecutorService threadLimit = Executors.newFixedThreadPool(10);
while(true) {
Socket s = serverSocket.accept();
treadLimit.submit(new HandleThread(s));
}
I'm trying to make a basic client <-> server connection in Java. When trying to write to the server, the client sends the details correctly, and the server stalls on reading it until the client output stream is closed. Though, once the output stream is closed it apparently closes the socket, and due to that the server can't reply to the client. Here's the main snippet of code that handles this interaction.
Client:
private void sendCmd(String cmd) {
String infoToSend = cmd;
try {
socket = new Socket(hostname, port);
System.out.println("Trying to send: " + com.sun.org.apache.xml.internal.security.utils.Base64.encode(infoToSend.getBytes()));
out = new DataOutputStream(socket.getOutputStream());
out.writeBytes(com.sun.org.apache.xml.internal.security.utils.Base64.encode(infoToSend.getBytes()));
out.flush();
System.out.println("Socket is flushed");
System.out.println("Waiting for Data");
InputStream is = socket.getInputStream();
System.out.println("Trying to get data");
BufferedReader input = new BufferedReader(
new InputStreamReader(is)
);
String line;
while((line = input.readLine()) != null) {
System.out.println(line);
}
socket.close();
} catch (IOException e) { e.printStackTrace(); }
}
Server:
public void run() {
System.out.println("Got Connection");
try {
BufferedReader in = new BufferedReader(new InputStreamReader(socket.getInputStream()));
out = new DataOutputStream(socket.getOutputStream());
String response;
System.out.println("Response:");
String decode = "";
while ((response = in.readLine()) != null) {
try {
decode = new String(Base64.decode(response));
} catch (Base64DecodingException e) {
e.printStackTrace();
}
}
System.out.println("Decoded: " + decode);
out.writeBytes("We got your message!");
out.flush();
out.close();
} catch (IOException e) { System.out.println("Fail"); e.printStackTrace(); }
Would anyone be able to guide me on how to fix this error. Sorry if it's super easy and I'm just unable to see it.
Sending
socket.shutdownOutput();
solved the issue.
I wanna write the code to let Client send a string to Server, Server print the string and reply a string, then Client print the string Server reply.
My Server
public class Server {
public static void main(String[] args) throws IOException {
ServerSocket ss = null;
Socket s = null;
try {
ss = new ServerSocket(34000);
s = ss.accept();
BufferedReader in = new BufferedReader(new InputStreamReader(
s.getInputStream()));
OutputStreamWriter out = new OutputStreamWriter(s.getOutputStream());
while (true) {
String string = in.readLine();
if (string != null) {
System.out.println("br: " + string);
if (string.equals("end")) {
out.write("to end");
out.flush();
out.close();
System.out.println("end");
// break;
}
}
}
} catch (IOException e) {
e.printStackTrace();
} finally {
s.close();
ss.close();
}
}
}
My Client:
public class Client {
public static void main(String[] args) {
Socket socket =null;
try {
socket = new Socket("localhost", 34000);
BufferedReader in =new BufferedReader(new InputStreamReader(socket.getInputStream()));
OutputStreamWriter out = new OutputStreamWriter(socket.getOutputStream());
String string = "";
string = "end";
out.write(string);
out.flush();
while(true){
String string2 = in.readLine();
if(string2.equals("to end")){
System.out.println("yes sir");
break;
}
}
} catch (Exception e) {
e.printStackTrace();
}finally{
try {
System.out.println("closed client");
socket.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
}
are there some somethings wrong? if i remove the code "while(true) ..." in client class, it's OK.
you should add "\r\n" at the end of the String which write into stream.
example:
client :
string = "end";
out.write(string + "\r\n");
out.flush();
server :
out.write("to end" + "\r\n");
out.flush();
out.close();
System.out.println("end");
// break;
I don't see the server response.
You do a
System.out.println("br: " + string);
but not a
out.write(string);
out.flush();
Appand "\n" to end of the response from server.
outToClient.writeBytes(sb.toString() + "\n");
You are reading lines but you aren't writing lines. Add a newline, or call BufferedReader.newLine().
I'm having problems with broadcasting the messages sent by each client. The server can receive each message from multiple clients but it cannot broadcast it. Error message says connection refused
Client:
public void initializeConnection(){
try {
host = InetAddress.getLocalHost();
try{
// Create file
FileWriter fstream = new FileWriter("src/out.txt", true);
BufferedWriter out = new BufferedWriter(fstream);
out.write(host.getHostAddress()+'\n');
//Close the output stream
out.close();
}catch (Exception e){//Catch exception if any
System.err.println("Error: " + e.getMessage());
}
clientSocket = new Socket(host.getHostAddress(), port);
outToServer = new PrintWriter(clientSocket.getOutputStream(), true);
inFromServer = new BufferedReader(new InputStreamReader(clientSocket.getInputStream()));
}
catch(IOException ioEx) {
ioEx.printStackTrace();
}
}
public void actionPerformed(ActionEvent e)
{
if(e.getSource()==quit){
try {
outToServer.close();
clientSocket.close();
System.exit(1);
} catch (IOException e1) {
e1.printStackTrace();
}
}
else if(e.getSource()==button){
if(outMsgArea.getText()!=null || !outMsgArea.getText().equals("")){
String message = outMsgArea.getText();
outToServer.println(clientName+": "+message);
outMsgArea.setText("");
}
}
}
public void run(){
try {
while(true){
String message = inFromServer.readLine();
System.out.println(message);
inMsgArea.append(message+'\n');
}
} catch (IOException e) {
e.printStackTrace();
}
}
Server:
import java.io.*;
import java.net.*;
import java.util.*;
public class RelayChatServer {
public static int port = 44442;
ServerSocket server;
public void listenSocket(){
try{
server = new ServerSocket(port);
} catch (IOException e) {
System.out.println("Could not listen on port 4444");
System.exit(-1);
}
while(true){
ClientWorker w;
try{
//server.accept returns a client connection
w = new ClientWorker(server.accept());
Thread t = new Thread(w);
t.start();
} catch (IOException e) {
System.out.println("Accept failed: 4444");
System.exit(-1);
}
}
}
protected void finalize(){
//Objects created in run method are finalized when
//program terminates and thread exits
try{
server.close();
} catch (IOException e) {
System.out.println("Could not close socket");
System.exit(-1);
}
}
public static void main(String[] args) {
new RelayChatServer().listenSocket();
}
}
class ClientWorker implements Runnable {
private Socket client;
//Constructor
ClientWorker(Socket client) {
this.client = client;
}
public void run(){
String line;
BufferedReader in = null;
PrintWriter out = null;
try{
in = new BufferedReader(new
InputStreamReader(client.getInputStream()));
//out = new
// PrintWriter(client.getOutputStream(), true);
} catch (IOException e) {
System.out.println("in or out failed");
System.exit(-1);
}
while(true){
try{
line = in.readLine();
//Send data back to client
//out.println(line);
//Append data to text area
if(line!=null && line!=""){
System.out.println(line);
try{
// Open the file that is the first
// command line parameter
FileInputStream fstream = new FileInputStream("out.txt");
BufferedReader br = new BufferedReader(new InputStreamReader(fstream));
String strLine;
//Read File Line By Line
Socket s;
PrintWriter prnt;
while ((strLine = br.readLine()) != null && (strLine = br.readLine()) != "") {
// Print the content on the console
s = new Socket(strLine, 44441);
prnt = new PrintWriter(s.getOutputStream(),true);
prnt.println(line);
System.out.println(strLine);
prnt.close();
s.close();
}
//Close the input stream
//inp.close();
}catch (Exception e){//Catch exception if any
System.err.println("Error: " + e.getMessage());
}
}
}catch (IOException e) {
System.out.println("Read failed");
e.printStackTrace();
System.exit(-1);
}
}
}
}
The Exception starts:
java.net.ConnectException: Connection refused: connect
The expanded output looks like:
I'm somewhat confused as to why you attempt to open a new socket (do you intend for this to be sent back to the client?) based on a string you read from a file. Perhaps
s = new Socket(strLine, 44441);
prnt = new PrintWriter(s.getOutputStream(),true);
should be:
prnt = new PrintWriter(client.getOutputStream(),true);
As currently I don't see where you are sending anything back to the client.
Edit: ok try something like the following:
static final ArrayList<ClientWorker> connectedClients = new ArrayList<ClientWorker>();
class ClientWorker implements Runnable {
private Socket socket;
private PrintWriter writer;
ClientWorker(Socket socket) {
this.socket = socket;
try {
this.writer = new PrintWriter(socket.getOutputStream(), true);
} catch (IOException ex) { /* do something sensible */ }
}
public void run() {
synchronized(connectedClients) {
connectedClients.add(this);
}
BufferedReader in = null;
try {
in = new BufferedReader(new InputStreamReader(socket.getInputStream()));
} catch (IOException e) { /* do something sensible */ }
while (true) {
try {
String line = in.readLine();
if (line != null && line != "") {
synchronized (connectedClients) {
for (int i = 0; i < connectedClients.size(); ++i){
ClientWorker client = connectedClients.get(i);
client.writer.println(line);
}
}
}
} catch (IOException e) { /* do something sensible */ }
}
}
}