does not read anything using ObjectInputStream in Java socket - java

I created a simple server and a client, but the server could not read anything that was sent from the client. I also add a print statement after I sent the string, but it cannot be printed either.
public class Server {
public static void main(String[] args) throws IOException, ClassNotFoundException {
ServerSocket serverSocket = new ServerSocket(6666);
Socket clientSocket = serverSocket.accept();
System.out.println("accepting client at address " + clientSocket.getRemoteSocketAddress());
ObjectInputStream in = new ObjectInputStream(clientSocket.getInputStream());
ObjectOutputStream out = new ObjectOutputStream(clientSocket.getOutputStream());
String input = (String) in.readObject();
System.out.println(input);
out.writeObject("Received");
out.flush();
}
}
Below is the client, and I just want to send a string "?????does not send":
public class Test {
public static void main(String[] args) throws IOException, ClassNotFoundException {
Client client = new Client();
client.sentInfo();
}
private static class Client {
private ObjectInputStream objectInputStream;
private ObjectOutputStream objectOutputStream;
public Client() throws IOException {
Socket socket = new Socket("127.0.0.1", 6666);
this.objectInputStream = new ObjectInputStream(socket.getInputStream());
this.objectOutputStream = new ObjectOutputStream(socket.getOutputStream());
}
public void sentInfo() throws IOException, ClassNotFoundException {
this.objectOutputStream.writeObject("?????does not send");
this.objectOutputStream.flush();
System.out.println("????????");
Message resp = (Message) this.objectInputStream.readObject();
System.out.println(resp.getMessage());
}
}
}
I tried something else, if I just use InputStream and use a buffer to read bytes, like this:
Server code
This is the client code: client code
The code in the two link above would work. However, it would not work if I tried to use ObjectInputStream:
This is the server: server
This is the client: client
This is the Message object I want to send: Message class
Can someone explain this for me please? Thanks!

To read Strings from a socket use something like this:
DataInputStream input = new DataInputStream(clientSocket.getInputStream());
String message = input.readUTF();
You can open multiple streams from a socket, so if you want to read something else that really needs the ObjectInputStream than it can be open as well. Don't forget to properly close the streams & sockets.

Related

How to give an automated response back when receiving a specific message from the client (Java, sockets)

I basically was trying to give a response back from my server if my client sends me the message "Hello mr server". However it doesn't.
Here is my code :
public class Server {
public static final int PORT = 6666;
public static void main(String[] args) throws IOException {
new Server().runServer();
}
public void runServer() throws IOException {
ServerSocket serverSocket = new ServerSocket(PORT);
System.out.println("Server up and ready for connections.....");
while (true) {
Socket socket = serverSocket.accept();
BufferedReader br = new BufferedReader(new InputStreamReader(socket.getInputStream())); //for fetching data
String str = br.readLine(); //for fetching data
System.out.println("Client Data:" + str + '\n');
String dataSendingToClient = "gg";
OutputStreamWriter os = new OutputStreamWriter(socket.getOutputStream()); //for sending data
PrintWriter out = new PrintWriter(os); //for sending data
out.println(dataSendingToClient);
os.flush();
if (br.equals("hey mr server")){
OutputStreamWriter os2 = new OutputStreamWriter(socket.getOutputStream()); //for sending data
PrintWriter out2 = new PrintWriter(os); //for sending data
out2.println("hey mr client");
os.flush();
}
}
}
}
You are using br.equals("hey mr server") which will always return false, since br is not a String, but a BufferedReader
Instead you should use your already defined str variable str.equals("hey mr server")
Also note that with your current code, your server will only read one message from the client before moving on to the next connection
If you want your server to read more messages from a single client, you will need to loop until the client sends a disconnect message/the socket closes
while(true)
{
Socket socket = serverSocket.accept();
BufferedReader br = [...];
PrintWriter out = [...];
for(String message = br.readLine(); message != null; message = br.readLine())
{
//do stuff
//message is each line from the client
}
}
If you have multiple clients trying to connect, you will need to multithread the connections
I would recommend a class to enclose the connection details and use Stacks to poll if the client sent data
public static void main(String[] args) //or whatever other method you're running in
{
List<Connection> clients = new ArrayList<Connection>(); //some data structure to hold the clients
//start accepting connections
new Thread(new Runnable()
{
public void run()
{
while(true)
Connection client = new Connection(serverSocket.accept());
}
}).start();
//do something with the clients, read/write/whatever
}
private class Connection extends Runnable
{
private BufferedReader reader;
private PrintWriter writer;
private Queue<String> messages;
public Connection(Socket s)
{
reader = [...];
writer = [...];
messages = new LinkedList<String>();
}
public void run()
{
//just keep reading
while(true)
messages.add(reader.readLine();
}
public String read()
{
messages.poll();
}
public void write(String msg)
{
writer.write(msg);
writer.flush();
}
}
Note: take that as rough pseudocode

Java: Send and recive an Object over Socket

I am a student and learning Network Programming and have a some problem.
This is my client:
public class Test2Client_Tranfer_An_Obj {
Socket socket = null;
ObjectOutputStream out;
ObjectInputStream in;
public Test2Client_Tranfer_An_Obj() {
try {
socket = new Socket("localhost", 12345);
out = new ObjectOutputStream(socket.getOutputStream());
in = new ObjectInputStream(socket.getInputStream());
System.out.println("Ready");
System.out.println("" + in.readUTF());
System.out.println("" + in.readUTF());
System.out.println("Recived");
out.writeUTF("hihi");
System.out.println("Sended");
} catch (Exception e) {
e.printStackTrace();
}
}
public static void main(String[] args) {
System.out.println("Client");
Test2Client_Tranfer_An_Obj test = new Test2Client_Tranfer_An_Obj();
}
}
This my Server:
public class Test2Server_Tranfer_An_Obj {
ServerSocket serverSocket;
ObjectOutputStream out;
ObjectInputStream in;
public Test2Server_Tranfer_An_Obj() {
try {
serverSocket = new ServerSocket(12345);
Socket socket = serverSocket.accept();
out = new ObjectOutputStream(socket.getOutputStream());
in = new ObjectInputStream(socket.getInputStream());
System.out.println("Ready!");
out.writeUTF("huhu");
out.writeUTF("hoho");
System.out.println("Sended");
String s = in.readUTF();
System.out.println("" + s);
System.out.println("Recived");
} catch (Exception e) {
e.printStackTrace();
}
}
public static void main(String[] args) {
System.out.println("Server");
Test2Server_Tranfer_An_Obj demo = new Test2Server_Tranfer_An_Obj();
}
}
But, when i run my program, this result:
Server Console
Server
Ready!
Sended
Client Console
Client Ready
Anybody can tell me why and what i can do?
Thank for reading!
Hope recive you answer
Object Stream is overkill in this case. You are not actually using writeObject/readObject and using DataInputStream and DataOutputStream would do what you want.
In this particular case, an Object Stream is buffered, which means that small writes are buffered until you either flush() or close() the stream to improve performance. As you don't do either, the writeUTF only writes to memory, not the Socket.
c.f. Data Streams are not buffered by default.
In your server after write to the outputstream. you have to add out.flush() to write to socket

How to make socket communications?

Recently I was looking at socket communications, and after I read few tutorials I came out with something like that.
public class Server{
public static void main(String[] args) throws IOException, InterruptedException {
ServerSocket server = new ServerSocket(9999);
Socket socket = server.accept();
PrintWriter out = new PrintWriter(socket.getOutputStream(), true);
BufferedReader in = new BufferedReader(new InputStreamReader(socket.getInputStream()));
String message = "";
int ch = -1;
while((ch=in.read())!= -1 ){
message+=ch;
}
// String message = in.readLine();
System.out.println("RECEIVED "+message);
out.write("RESPONSE "+message+"\n");
out.flush();
System.out.println("NEW MESSAGE SEND");
Thread.sleep(3000);
System.out.println("CLOSE");
server.close();
}
}
public class Client {
public static void main(String[] args) throws UnknownHostException, IOException {
Socket socket = new Socket("127.0.0.1", 9999);
PrintWriter out = new PrintWriter(socket.getOutputStream(), true);
out.write("MESSAGE\n");
out.flush();
System.out.println("SEND MESSAGE");
BufferedReader in = new BufferedReader(new InputStreamReader(socket.getInputStream()));
System.out.println(in.readLine());
socket.close();
}
}
After I run this code, Client logs "SEND MESSAGE" while server hangs on in.read() and does not receiving any message.
Can anyone help me and explain me what I'm doing wrong?
Your server is reading from the socket until end of stream. End of stream only occurs when the peer closes the connection. At that point you will be unable to send a reply. You need to reconsider your protocol. For a simple example you could read and write lines, one at a time, as you are in the client.

can i use multiple times (input/output)stream for different types of data transfer between two nodes [duplicate]

This question already has answers here:
Java multiple file transfer over socket
(3 answers)
Closed 6 years ago.
In this code I use multiple times of retrieve input-output data from two nodes. ... when I use more than two times input output stream it generated this type of error while running this code I need different input and output and that I want to store but unfortunate if I used more than three-time input/output stream it show error
public class Server {
private static Socket socket;
public void connect() throws IOException{
int port = 25000;
ServerSocket serverSocket = new ServerSocket(port);
System.out.println("Server Started and listening to the port 25000");
socket = serverSocket.accept();
}
//Server is running always. This is done using this while(true) loop
//Reading the message from the client
public void first() throws IOException{
connect();
InputStream is = socket.getInputStream();
InputStreamReader isr = new InputStreamReader(is);
BufferedReader br = new BufferedReader(isr);
String number = br.readLine();
System.out.println("Message received from client is "+number);
//Multiplying the number by 2 and forming the return message
String returnMessage;
try
{
int numberInIntFormat = Integer.parseInt(number);
int returnValue = numberInIntFormat*2;
returnMessage = String.valueOf(returnValue) + "\n";
}
catch(NumberFormatException e)
{
//Input was not a number. Sending proper message back to
client.
returnMessage = "Please send a proper number\n";
}
second();
String e=br.readLine();System.out.println(e);
}
public void second() throws IOException{
//Sending the response back to the client.
String returnMessage="Second";
OutputStream os = socket.getOutputStream();
OutputStreamWriter osw = new OutputStreamWriter(os);
BufferedWriter bw = new BufferedWriter(osw);
bw.write(returnMessage);
System.out.println("Message sent to the client is "+returnMessage);
bw.flush();
}
public static void main(String args[]) throws IOException{
Server obj = new Server();
obj.first();
// obj.second();
}public class Server {
private static Socket socket;
public void connect() throws IOException{
int port = 25000;
ServerSocket serverSocket = new ServerSocket(port);
System.out.println("Server Started and listening to the port 25000");
socket = serverSocket.accept();
}
//Server is running always. This is done using this while(true) loop
//Reading the message from the client
public void first() throws IOException{
connect();
InputStream is = socket.getInputStream();
InputStreamReader isr = new InputStreamReader(is);
BufferedReader br = new BufferedReader(isr);
String number = br.readLine();
System.out.println("Message received from client is "+number);
//Multiplying the number by 2 and forming the return message
String returnMessage;
try
{
int numberInIntFormat = Integer.parseInt(number);
int returnValue = numberInIntFormat*2;
returnMessage = String.valueOf(returnValue) + "\n";
}
catch(NumberFormatException e)
{
//Input was not a number. Sending proper message back to client.
returnMessage = "Please send a proper number\n";
}
second();
String e=br.readLine();System.out.println(e);
}
public void second() throws IOException{
//Sending the response back to the client.
String returnMessage="Second";
OutputStream os = socket.getOutputStream();
OutputStreamWriter osw = new OutputStreamWriter(os);
BufferedWriter bw = new BufferedWriter(osw);
bw.write(returnMessage);
System.out.println("Message sent to the client is "+returnMessage);
bw.flush();
}
public static void main(String args[]) throws IOException{
Server obj = new Server();
obj.first();
// obj.second();
}
public class client {
private static Socket socket;
//public void connect() throws UnknownHostException, IOException{
//}
public void first() throws IOException{
String host = "localhost";
int port = 25000;
InetAddress address = InetAddress.getByName(host);
socket = new Socket(address, port);
OutputStream os = socket.getOutputStream();
OutputStreamWriter osw = new OutputStreamWriter(os);
BufferedWriter bw = new BufferedWriter(osw);
String number = "2";
String sendMessage = number + "\n";
bw.write(sendMessage);
bw.flush();
System.out.println("Message sent to the server : "+sendMessage);
String sendMessage1="3333";
bw.write(sendMessage1);
bw.flush();
//second();
}
public void second1() throws IOException{
//Get the return message from the server
InputStream is = socket.getInputStream();
InputStreamReader isr;
isr = new InputStreamReader(is);
BufferedReader br = new BufferedReader(isr);
String message = br.readLine();
System.out.println("Message received from the server : " +message);
socket.close();
}
public static void main (String argd[]) throws IOException{
client obj1 = new client();
obj1.first();
}
-----------------------------------------
error
Message received from client is 2
Message sent to the client is Second
Exception in thread "main" java.net.SocketException: Connection reset
at java.net.SocketInputStream.read(SocketInputStream.java:209)
at java.net.SocketInputStream.read(SocketInputStream.java:141)
at sun.nio.cs.StreamDecoder.readBytes(StreamDecoder.java:284)
InputStream and OutputStream are intended to work with a single source and destination. Once you obtain an InputStream that reads from file/socket/whatever source you can use it for multiple consecutive reads. But once you are done reading from that source you need to invoke close() method on your stream.
Not closing your stream is classic reason for a memory leak in Java. In fact for that reason you ALWAYS expected to surround the usage of your source with try catch and always invoke close() method in finally statement. So to insure that it is always invoked. Further more, since close() method itself can cause an Exception, within final statement you need to surround it with its own try-catch. Starting from java 7 there is a new feature called "try with resources" that deals with this particular issue.
Please read about it here

Reading and writing from a socket produces no output?

I'm creating an application which will need to transmit data back and forth between multiple computers on a network. Because of the way the data is to be sent, the client computers will be running the socket server, and the coordinating computer will be running the client socket.
I've created simple classes which are simply intended to encapsulate reading from and writing to these sockets. However, instead of reading anything, the receiving socket simply outputs nothing. I have confirmed that both client and server have a connection.
In the following Server and Client classes, the Socket is made public for debugging purposes only.
public class Server {
public Socket client;
private DataInputStream inStr;
private PrintStream outStr;
public Server() throws UnknownHostException, IOException {this("localhost");}
public Server(String hostname) throws UnknownHostException, IOException {
client = new Socket(hostname, 23);
inStr = new DataInputStream(client.getInputStream());
outStr = new PrintStream(client.getOutputStream());
}
public void send(String data) {outStr.print(data); outStr.flush();}
public String recv() throws IOException {return inStr.readUTF();}
}
The following is my Client:
public class Client {
private ServerSocket serv;
public Socket servSock;
private DataInputStream inStr;
private PrintStream outStr;
public Client() throws IOException {
serv = new ServerSocket(23);
servSock = serv.accept();
inStr = new DataInputStream(servSock.getInputStream());
outStr = new PrintStream(servSock.getOutputStream());
}
public void send(String data) {outStr.print(data); outStr.flush();}
public String recv() throws IOException {return inStr.readUTF();}
}
The Client class is instantiated, and the program started. Then, in a separate program, the Server is instantiated and started:
Server s = new Server(); System.out.println(s.client.isConnected());
while(true) {System.out.println(s.recv()); Thread.sleep(200);}
Client c = new Client(); System.out.println(c.servSock.isConnected());
while(true) {c.send("Hello World!"); Thread.sleep(200);}
isConnected() returns true for both the Client and the Server.
What could be causing this? I've never had to use sockets before now.
DataInputStream.readUTF() expects the first two bytes to be the number of bytes to read, but PrintStream.print(String) will convert the string to bytes and write them as-is.
DataOutputStream.writeUTF(String) will write the length like readUTF() expects.

Categories