Sending and reading string to/from PrintWriter and BufferedReader - java

I have a server client that sends and receives info from the server socket using a PrintWriter for outgoing messages and a BufferedReader for incoming messages. I'm trying to test the client without a server connection in JUnit by sending strings to the client through the BufferedReader and reading the returned output from the PrintWriter.
class Client{
private BufferedReader incomingMessage;
private PrintWriter outgoingMessage;
private StringWriter output;
//Constructor for testing without server connection
public Client(){
output = new StringWriter();
outgoingMessage = new PrintWriter(output);
incomingMessage = new BufferedReader(new InputStreamReader(System.in));
}
//Methods for processing incoming messages and sending responses are
//omitted
//responses are sent using outgoingMessage.println("msg");
public void sendStringToInputStream(String msg){
incomingMessage = new BufferedReader(new StringReader(msg));
}
public String getOutputAsString(){
return output.toString();
}
}
This is the test I'm running.
public class ServerMessageTest {
private Client testClient;
private String output;
#Before
public void setUp(){
testClient = new Client();
}
#Test
public void testClientOutputMessage(){
testClient.sendStringToInputStream("GAME A OVER SEND OUTCOME");
output = testClient.getOutputAsString();
String testString = "GAME A OVER PLAYER 1 0 PLAYER 2 0";
Assert.assertEquals(testString, output.toString());
}
}
The test fails showing this:
org.junit.ComparisonFailure:
Expected :GAME A OVER PLAYER 1 0 PLAYER 2 0
Actual :
So there's an issue with reading the output message or setting the input message. I'm kinda new to IO stuff, so if someone could point out what I'm doing wrong I would greatly appreciate it!

Your variable names are bizarre. A BufferedReader isn't a message, and neither is a PrintWriter.
You aren't doing any output or input in this code. You need to call println() to send the message, and readLine() to receive it. Converting the reader and writer to strings accomplishes exactly nothing.
You need to create your reader and writer once per socket, not once per message.

Related

Java, SSLSocket, receiving no answer

I'm trying to use SSL with IMAP in java. I do not want to use the IMAP class.
For some reason, when I send the n th message, I receive the answer to message n-2, and not to message n-1. Which means that I don't receive any answer to the first message sent until I send the second message. Can anyone spot what's wrong in the following minimal code ? (It is indeed minimal, apart from the println, which, I guess, help debugging)
import java.io.*;
import javax.net.ssl.*;
public class Mail{
static String server = "imap.gmail.com";
static String user = "straightouttascript#gmail.com";
static String pass = "azerty75";
public static void print (PrintWriter to, String text){
System.out.println("sent : "+text);
to.println(text+ "\r");
to.flush();
}
public static void read (BufferedReader from) throws InterruptedException, IOException {
do {
String line = from.readLine();
System.out.println("received: "+line);
} while (from.ready());
}
public static void main(String[] args){
try{
SSLSocket sslsocket = (SSLSocket) SSLSocketFactory.getDefault().createSocket(server, 993);
System.out.println("Start connexion");
BufferedReader from = new BufferedReader(new InputStreamReader(sslsocket.getInputStream()));
// read(from);
PrintWriter to = new PrintWriter(new BufferedWriter(new OutputStreamWriter(sslsocket.getOutputStream())), true);
print(to,"a1 login "+user+" "+pass);
read(from);/*exepcted:
OK gimap ready
a1 OK login#host authenticated (Success)*/
sslsocket.close();
System.out.println("End connexion");
}
catch (Exception e){
e.printStackTrace();
}
}
}
IMAP is not a pingpong protocol. The server doesn't send one line in response to one of yours.
Rather, you send commands and the server sends information. The server is permitted to send you more information than you asked for, so you can get seven responses to one command, and you can even get a response without sending a command at all, which is then called an unsolicited response. Strange phrase. Unsolicited responses are used by some servers to notify you about new mail, by more to notify you about flag changes on messages, and by (almost?) all to notify you that they're about to close your connection.

Null Pointer Exception while trying to run Java multi threaded server

I'm trying to write a java message switch application by using a multi-threaded server and two clients. However I'm stuck at one point as error occurs when I try to run my programmes. Here are my codes for the server:
public class EchoServer extends Thread {
private static ServerSocket serverSocket;
private static Socket connection1;
private static Socket connection2;
private BufferedReader input;
private PrintWriter output;
final static int portNumber = 4434;
public EchoServer(Socket in,Socket out) throws IOException{
connection1 = serverSocket.accept();
connection2 = serverSocket.accept();
input = new BufferedReader(new InputStreamReader(in.getInputStream()));
output = new PrintWriter(out.getOutputStream(),true);
}
public void run()
{
String inputLine;
while((inputLine=input.readLine())!=null){
if(inputLine.equalsIgnoreCase("quit"))
break;
System.out.println("received:" + inputLine);
output.println(inputLine);
}
System.out.println("received quit,exiting");
}
public static void main(String args[]){
serverSocket = new ServerSocket(portNumber);
System.out.println("listening on port:"+ portNumber);
EchoServer echoserver1 = new EchoServer(connection1,connection2);
EchoServer echoserver2 = new EchoServer(connection2,connection1);
echoserver1.start();
echoserver2.start();
}
}
I also wrote two classes for client. When I run the server and then the first client, they work as expected. However when I try to run the second client, a NullPointerException is thrown, regarding to the following two lines:
input = new BufferedReader(new InputStreamReader(in.getInputStream()));
EchoServer echoserver1 = new EchoServer(connection1,connection2);
I know it's a rather long piece of codes to look at, but I'm really stuck as I can't see the problem here. The earlier single threaded version of server I wrote worked without error, so I know there's something to do about the multithreaded. Any help and advice is really appreciated. Thanks!
connection1 and connection2 are never initialized in your main method, hence you get a NullPointerException when you call in.getInputStream() in your constructor.
Not completely sure what you're trying to achieve, but looks like you might want to move these two lines
connection1 = serverSocket.accept();
connection2 = serverSocket.accept();
to your main method.

How to serialize a object in the HttpHandler class

I have to serialize an object and send it from a httpserver
i already know how to send a string from the server to the client,but i don't know how to send a object
So i have this code :
public class Test {
public static void main(String[] args) throws Exception {
HttpServer server = HttpServer.create(new InetSocketAddress(8000), 0);
server.createContext("/test", new MyHandler());
server.setExecutor(null); // creates a default executor
server.start();
}
static class MyHandler implements HttpHandler {
public void handle(HttpExchange t) throws IOException {
String response = "This is the response";
//this part here shows how to send a string
//but i need to send an object here
t.sendResponseHeaders(200, response.length());
OutputStream os = t.getResponseBody();
os.write(response.getBytes());
os.close();
}
}
}
so i tried to search google but no results,and i tried to change the code (mechanically without knowing well what im doing as im not used to HttpServer's in java)
this way :
SendResponse obj = new SendResponse();
ObjectOutputStream objOut = new ObjectOutputStream();
t.sendResponseHeaders(200, objOut);
objOut.writeObject(obj);
objOut.close();
but eclipse shows me an error which tells me that the ObjectOutputStream() constructor is not visible and that httpExchange is not applicable for the arguments (int,ObjectInputStream)
Do you have any idea how i can fix this ?
Thank you in advance for your help !
You have accesible the constructor with one OutputStream as parameter
ObjectOutputStream objOut = new ObjectOutputStream( the http or any other output stream here );
The constructor of ObjectOutputStream sends some header bytes and the constructor of ObjectInputStream expects these header bytes. You should either create a new ObjectOutputStream and a new ObjectInputStream for every object, or create only one ObjectOutputStream and ObjectInputStream for all the objects.
A more simple alternative could be google gson It´s easy to use and it converts a java class to json string and the inverse way too.
After some hours of trying different things
you have just to replace the
t.sendResponseHeaders(200, objOut);
with
t.sendResponseHeaders(200,0);
as mentioned by user cyon on this question

DataOutputStream not emptying buffer

I am working on a server/client communication program and I am stuck at a problem. When I try to send messages from my client side it won't work properly. After initializing the server, I connect the client and that is successful. When I try to send messages from the client, the server won't receive them. After I close the client connection, the server receives all of the messages I attempted to send earlier. The following class is what I am using:
public class ServerSender extends Thread
{
private DataOutputStream out = new DataOutputStream(socket.getOutputStream());
private Scanner kb = new Scanner(System.in);
public void run()
{
while(true)
{
try
{
out.writeUTF(kb.nextLine());
out.flush();
} catch(IOException e) { System.out.println("error"); }
}
}
}
Any help would be much appreciated, thanks.
DataOutputStream doesn't have a buffer to flush, so your diagnosis is incorrect. However you need to be aware that writeUTF() writes a format that only DataInputStream.readUTF() can read. If you're trying to write lines you have the wrong API: try BufferedWriter.write()/.newLine().

TCP Client/Server communication only sends first message?

I am setting up a simple TCP Client Server interaction in java.
Server:
The server is a desktop client written in Java:
import java.io.BufferedReader;
import java.io.DataOutputStream;
import java.io.InputStreamReader;
import java.net.ServerSocket;
import java.net.Socket;
class TCPServer
{
public static int PORT_NUMBER = 6129;
public static void main(String argv[]) throws Exception
{
String clientMessage;
ServerSocket welcomeSocket = new ServerSocket(PORT_NUMBER);
while (true)
{
Socket connectionSocket = welcomeSocket.accept();
BufferedReader inFromClient = new BufferedReader(new InputStreamReader(connectionSocket.getInputStream()));
DataOutputStream outToClient = new DataOutputStream(connectionSocket.getOutputStream());
clientMessage = inFromClient.readLine();
System.out.println("Received: " + clientMessage);
outToClient.writeBytes("I received this: "+ clientMessage +"\n");
}
}
}
Client:
The client is an android app that connects to the server with TCP. In the client I have a method sendMessage(String msg) which attempts to send a message to the server.
public static void sendMessage(String msg) throws IOException
{
if (mainSocket == null)
{
return;
}
if (!mainSocket.isConnected())
{
connectSocket();
}
PrintWriter output = new PrintWriter( mainSocket.getOutputStream());
output.println(msg);
output.flush();
System.out.println(msg);
}
The problem is, the server receives the first message, but any subsequent messages won't show up at all. When I close the client down, all of a sudden all the other messages show up at once in the server.
This is what the server sees:
Received: message 1
No activity for a long time...
Then I shut down the client
Received: message 2 message 3 message 4 message 5 etc..
I put a println in the sendMessage() method, and the method itself is being called in real time.
You need to explicitly close() your PrintWriter on the client side each time you send a message. Same on the server side when you are done reading inFromClient, and again when you are done writing to outToClient.
See also this basic example, they explain the basic workflow quite nicely:
However, the basics are much the same as they are in this program:
Open a socket.
Open an input stream and output stream to the socket.
Read from and write to the stream according to the server's protocol.
Close the streams.
Close the socket.

Categories

Resources