I am learning Java and I'm writing an example client - server application.
The sokcket connection is fine, everything works well until the second message from the client app. It does not reach the server. If I start another client it also succeed at the first message, and fails at the second.
Anyone has an idea? Thanks in advance!
Server code:
package networking;
import java.io.BufferedReader;
import java.io.BufferedWriter;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.OutputStream;
import java.io.OutputStreamWriter;
import java.net.ServerSocket;
import java.net.Socket;
public class Server {
private static Socket socket;
public static void main(String[] args) {
try {
int port = 25000;
ServerSocket serverSocket = new ServerSocket(port);
System.out.println("Server Started and listening to the port 25000");
//Server is running always. This is done using this while(true) loop
while (true) {
//Reading the message from the client
socket = serverSocket.accept();
InputStream is = socket.getInputStream();
InputStreamReader isr = new InputStreamReader(is);
BufferedReader br = new BufferedReader(isr);
String incomingMessage = br.readLine();
System.out.println("((( " + incomingMessage);
String returnMessage = incomingMessage;
//Sending the response back to the client.
OutputStream os = socket.getOutputStream();
OutputStreamWriter osw = new OutputStreamWriter(os);
BufferedWriter bw = new BufferedWriter(osw);
bw.write(returnMessage + "\n");
bw.flush();
System.out.println("))) " + returnMessage);
}
} catch (Exception e) {
e.printStackTrace();
} finally {
try {
socket.close();
} catch (Exception e) {
}
}
}
}
And the client
package networking;
import java.io.BufferedReader;
import java.io.BufferedWriter;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.OutputStream;
import java.io.OutputStreamWriter;
import java.net.ServerSocket;
import java.net.Socket;
public class Client {
private static Socket socket;
public static void main(String args[]) {
try {
String host = "localhost";
int port = 25000;
InetAddress address = InetAddress.getByName(host);
socket = new Socket(address, port);
//Send the message to the server
OutputStream os = socket.getOutputStream();
OutputStreamWriter osw = new OutputStreamWriter(os);
BufferedWriter bw = new BufferedWriter(osw);
BufferedReader console = new BufferedReader(new InputStreamReader(System.in));
InputStream is = socket.getInputStream();
InputStreamReader isr = new InputStreamReader(is);
BufferedReader br = new BufferedReader(isr);
String message = "";
/*
while(!message.equals("q")) {
System.out.print("Message: ");
message = console.readLine();
bw.write(message + "\n");
bw.flush();
System.out.println("))) " + message);
//Get the return message from the server
String incomingMessage = br.readLine();
System.out.println("((( " + incomingMessage);
}
*/
for (int i = 0; i < 10; i++) {
bw.write(i + "\n");
bw.flush();
System.out.println("))) " + i);
String incomingMessage = br.readLine();
System.out.println("((( " + incomingMessage);
}
} catch (Exception exception) {
exception.printStackTrace();
} finally {
//Closing the socket
try {
socket.close();
} catch (Exception e) {
e.printStackTrace();
}
}
}
}
Your while is misplaced in your server code, and in fact you need 2 while loops:
one for accepting new clients
one for manage several messages by client
In pseudo code it gives you:
while (true):
accept new client
while (client connected):
read message from client
write back message to client
close client socket
If you want to use threads, then it's the inner while loop task which you have to delegate to a new thread.
Note: accept is blocking until a new client comes. That why you could send only one message by client.
Your server is not set up to handle this. You are reading one line, then discarding the connection for the GC, without closing it. The server, reading one line, then ignores all other lines and starts listening for the next connection.
Also, consider using threads.
Related
I created a SOA service with Socket Adapter on JDeveloper and I need to run/test it using Java. So I created a server class and a client class but I am getting an error
I did some research on how to create this service and test it and I came across some helpful material online but yet I'm getting an error and I dont know how to fix it. I am very new to making socket servers and stuff.
here is my server class
package client;
import java.net.ServerSocket;
import java.net.Socket;
public class Class1 {
try {
ServerSocket socket = new ServerSocket(12110);
Socket s=socket.accept();
System.out.println("Connected!");
} catch (Exception e) {
e.printStackTrace();
}
}
}
and here is my client class
package client;
import java.io.BufferedReader;
import java.io.InputStreamReader;
import java.io.OutputStream;
import java.net.Socket;
public class Client{
public static void main(String[] args) {
try {
Socket socket = new Socket("localhost", 12110);
OutputStream os = socket.getOutputStream();
os.write("FirstName,LastName\nWaslley,Souza\nJohn,Snow".getBytes());
os.flush();
socket.shutdownOutput();
BufferedReader soc_in = new BufferedReader(new InputStreamReader(socket.getInputStream()));
String response = soc_in.readLine();
System.out.println("Response: " + response);
socket.close();
} catch (Exception e) {
e.printStackTrace();
}
}
}
here is the error I get:
java.net.SocketException: Connection reset
at java.net.SocketInputStream.read(SocketInputStream.java:210)
at java.net.SocketInputStream.read(SocketInputStream.java:141)
at sun.nio.cs.StreamDecoder.readBytes(StreamDecoder.java:284)
at sun.nio.cs.StreamDecoder.implRead(StreamDecoder.java:326)
at sun.nio.cs.StreamDecoder.read(StreamDecoder.java:178)
at java.io.InputStreamReader.read(InputStreamReader.java:184)
at java.io.BufferedReader.fill(BufferedReader.java:161)
at java.io.BufferedReader.readLine(BufferedReader.java:324)
at java.io.BufferedReader.readLine(BufferedReader.java:389)
at client.Client.main(Client.java:23)
This happens because your server code exits after accepting a socket connection. Consequently, the JVM of this server will exit and (among others) close all socket connections it holds. This results in a SocketException on the client side.
To fix this, you should prevent the server's JVM from exiting, for instance by nesting the accept() call in a while loop:
public class Server {
public static void main(String[] args) {
try {
ServerSocket socket = new ServerSocket(12110);
while (true) {
Socket s = socket.accept();
System.out.println("Connected! to " + s);
}
} catch (final Exception e) {
e.printStackTrace();
}
}
}
Server Code:
import java.io.IOException;
import java.io.ObjectInputStream;
import java.io.ObjectOutputStream;
import java.net.ServerSocket;
import java.net.Socket;
public class Class1 {
//static ServerSocket variable
private static ServerSocket server;
//socket server port on which it will listen
private static int port = 12110;
public static void main(String args[]) throws IOException, ClassNotFoundException {
//create the socket server object
server = new ServerSocket(port);
//keep listens indefinitely until receives 'exit' call or program terminates
while (true) {
System.out.println("Waiting for the client request");
//creating socket and waiting for client connection
Socket socket = server.accept();
//read from socket to ObjectInputStream object
ObjectInputStream ois = new ObjectInputStream(socket.getInputStream());
//convert ObjectInputStream object to String
String message = (String) ois.readObject();
System.out.println("Message Received: " + message);
//create ObjectOutputStream object
ObjectOutputStream oos = new ObjectOutputStream(socket.getOutputStream());
//write object to Socket
oos.writeObject("Hi Client " + message);
//close resources
ois.close();
oos.close();
socket.close();
//terminate the server if client sends exit request
if (message.equalsIgnoreCase("exit")) {
break;
}
}
System.out.println("Shutting down Socket server!!");
//close the ServerSocket object
server.close();
}
}
Client Code:
import java.io.IOException;
import java.io.ObjectInputStream;
import java.io.ObjectOutputStream;
import java.net.InetAddress;
import java.net.Socket;
import java.net.UnknownHostException;
public class Client {
public static void main(String[] args) throws UnknownHostException, IOException, ClassNotFoundException, InterruptedException {
//get the localhost IP address, if server is running on some other IP, you need to use that
InetAddress host = InetAddress.getLocalHost();
Socket socket = null;
ObjectOutputStream oos = null;
ObjectInputStream ois = null;
//establish socket connection to server
socket = new Socket(host.getHostName(), 12110);
//write to socket using ObjectOutputStream
oos = new ObjectOutputStream(socket.getOutputStream());
System.out.println("Sending request to Socket Server");
oos.writeObject("SEND SOME DATA");
//read the server response message
ois = new ObjectInputStream(socket.getInputStream());
String message = (String) ois.readObject();
System.out.println("Message: " + message);
//close resources
ois.close();
oos.close();
Thread.sleep(100);
}
}
do in this way.
yo #Mike sorry was not clear last time dig in this is the full server code
import java.net.ServerSocket;
import java.net.Socket;
import java.io.*;
public class Serv1 {
public static void main(String[] args) {
new Serv1().start();
}
public void start(){
String input = "";
try(ServerSocket socket = new ServerSocket(12110)) {
System.out.println("Connected!");
while (true) {
try(Socket server = socket.accept()){
BufferedReader in = new BufferedReader(new InputStreamReader(server.getInputStream(), "UTF-8"));
PrintStream echo = new PrintStream(server.getOutputStream());
while ((input = in.readLine()) != null && !input.equals(".")) {
System.out.println(input);
echo.println("Echoed: " + input);
}
}
}
} catch (Exception e) {
e.printStackTrace();
}
}
}
This should do it
String input= "";
Socket server=socket.accept();
BufferedReader in = new BufferedReader(new InputStreamReader(server.getInputStream(), "UTF-8"));
PrintStream echo = new PrintStream(server.getOutputStream());
while((input = in.readLine()) != null && !input.equals(".")) {
System.out.println(input);
echo.println("echo: "+input);
}
I am trying to write a simple and basic Java program where a client sends the server a string and the server is supposed to respond with a reversed string. I am sure I have the correct program structure and flow but my server is not read the string from my client. I have narrowed the problem to this line on the server side: string = inputStream.readLine();
Here is my code. What could be the problem?
Server1.java
import java.io.*;
import java.net.*;
class Server1 {
public static void main(String[] args) throws Exception {
String string = null;
ServerSocket myServerSocket = new ServerSocket(4000); //Create Socket
System.out.println("Server Running...");
Socket clientSocket = myServerSocket.accept();
DataInputStream inputStream = new DataInputStream(clientSocket.getInputStream());
PrintStream outputStream = new PrintStream(clientSocket.getOutputStream());
do {
string = inputStream.readLine();
if(string!=null){
//using StringBuilder method to reverse string
StringBuilder input = new StringBuilder();
// append a string into StringBuilder input1
input.append(input);
// reverse StringBuilder input1
input = input.reverse();
// print reversed String
for (int i = 0; i < input.length(); i++) {
outputStream.println(input.charAt(i));
}
}
} while (true);
/*outputStream.println("exit");
outputStream.close();
inputStream.close();
myServerSocket.close();
System.out.println("Server Closed!");*/
}
}
Client1.java
import java.io.*;
import java.net.*;
import java.util.Scanner;
class Client1 {
public static void main(String[] args) throws Exception {
Scanner sc = new Scanner(System.in); //Object to read keyboard input
String string = null, response = null; //Variable to store string
Socket mySocket = new Socket("127.0.0.1", 4000); //Create Socket
DataOutputStream outputStream = new DataOutputStream(mySocket.getOutputStream());
DataInputStream inputStream = new DataInputStream(mySocket.getInputStream());
System.out.println("Client Running...");
do {
System.out.println("Type in a string and Press Enter...");
string = sc.next();
outputStream.writeBytes(string);
response = inputStream.readLine();
if (response != null) {
System.out.println("Server Response: " + response);
}
} while (true);
}
}
The problem is that in this line string = inputStream.readLine();
it is searching for a line and if you wont add "\r\n" at the end of your massage it will keep searching for the lines end
I am trying to write a simple and basic Java program where a client
sends the server a string and the server is supposed to respond with a
reversed string. I am sure I have the correct program structure and
flow but my server is not read the string from my client. I have
narrowed the problem to this line on the server side: string =
inputStream.readLine(); Here is my code. What could be the problem?
Here, I can see copy paste mistake.
// append a string into StringBuilder input1
input.append(input);
Always use while(true) loop for reading message from the client,
Try below codes as for your question.
Server1.java
import java.io.BufferedReader;
import java.io.BufferedWriter;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.OutputStream;
import java.io.OutputStreamWriter;
import java.net.ServerSocket;
import java.net.Socket;
public class Server1 {
private static Socket socket;
public static void main(String[] args) {
try {
ServerSocket serverSocket = new ServerSocket(4000);
System.out.println("Server Running...");
//Note: Server is running always. This is done using this while(true) loop
while (true) {
//Reading the message from the client
socket = serverSocket.accept();
InputStream is = socket.getInputStream();
InputStreamReader isr = new InputStreamReader(is);
BufferedReader br = new BufferedReader(isr);
String string = br.readLine();
System.out.println("Message received from client is " + string);
//Reverse string responce builder
try {
//using StringBuilder method to reverse string
StringBuilder input = new StringBuilder();
// append a string into StringBuilder input
input.append(string);
// reverse StringBuilder input
input = input.reverse();
string = input + "\n"; //Next to line
// print reversed String
for (int i = 0; i < input.length(); i++) {
System.out.println(input.charAt(i));
}
} catch (Exception e) {
//Invalid text message back to client.
string = "Please send a proper text message\n";
}
//Sending the response back to the client.
OutputStream os = socket.getOutputStream();
OutputStreamWriter osw = new OutputStreamWriter(os);
BufferedWriter bw = new BufferedWriter(osw);
bw.write(string);
System.out.println("Message sent to the client is " + string);
bw.flush();
}
} catch (Exception e) {
e.printStackTrace();
} finally {
try {
socket.close();
} catch (Exception e) {
}
}
}
}
Client1.java
import java.io.BufferedReader;
import java.io.BufferedWriter;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.OutputStream;
import java.io.OutputStreamWriter;
import java.net.Socket;
import java.util.Scanner;
public class Client1 {
private static Socket socket;
public static void main(String args[]) {
try {
socket = new Socket("127.0.0.1", 4000);
System.out.println("Client Running...");
//Send the message to the server
OutputStream os = socket.getOutputStream();
OutputStreamWriter osw = new OutputStreamWriter(os);
BufferedWriter bw = new BufferedWriter(osw);
System.out.println("Type in a string and Press Enter...");
Scanner sc = new Scanner(System.in);
String string = sc.next();
System.out.println("string = " + string);
String sendMessage = string + "\n"; ////Next to line
bw.write(sendMessage);
bw.flush();
System.out.println("Message sent to the server : " + sendMessage);
//Get the return message from the server
InputStream is = socket.getInputStream();
InputStreamReader isr = new InputStreamReader(is);
BufferedReader br = new BufferedReader(isr);
String message = br.readLine();
System.out.println("Message received from the server : " + message);
} catch (Exception exception) {
exception.printStackTrace();
} finally {
//finally close the socket
try {
socket.close();
} catch (Exception e) {
e.printStackTrace();
}
}
}
}
server class :
the program is about to receive data from client and then reply. the server is okay..., but the problem is when the server send the reply to the client. the client always says 'the socket is close'. i try to delete secket close statement but the result is same.., the output says that 'the socket is close'. so please help me to solve this problem...
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.OutputStream;
import java.io.PrintStream;
import java.net.BindException;
import java.net.ServerSocket;
import java.net.Socket;
public class Nomor3Server {
public static final int SERVICE_PORT = 2020;
public static void main(String[] args) {
try {
ServerSocket server = new ServerSocket(SERVICE_PORT);
System.out.println("DAytime service started");
for (;;) {
Socket nextClient = server.accept();
BufferedReader pesan = new BufferedReader(new InputStreamReader(nextClient.getInputStream()));
String messageIn = pesan.readLine();
System.out.println("Received request from "
+ nextClient.getInetAddress() + " : "
+ nextClient.getPort()
+ "\nIsi Pesan : " + messageIn);
String messageOut = "انا لا ادر";
switch (messageIn) {
case "saya":
messageOut = "أنا";
break;
case "kamu":
messageOut = "أنت";
break;
default:
break;
}
OutputStream out = nextClient.getOutputStream();
PrintStream pout = new PrintStream(out);
pout.print(messageOut);
out.flush();
out.close();
System.out.println("Message sent");
//nextClient.close();
}
} catch (BindException e) {
System.err.println("Server Already Running on port : " + SERVICE_PORT);
} catch (IOException ioe) {
System.err.println("error : " + ioe);
}
}
}
client class :
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.OutputStream;
import java.io.PrintStream;
import java.net.Socket;
public class Nomor3Client {
public static final int SERVICE_PORT = 2020;
public static void main(String[] args) {
try {
String hostname = "localhost";
System.out.println("Connection Established");
//for (;;) {
System.out.println("Enter Your Message : ");
BufferedReader read = new BufferedReader(new InputStreamReader(System.in));
String pesan = read.readLine();
Socket daytime = new Socket(hostname, SERVICE_PORT);
if (pesan.equals("exit")) {
System.exit(0);
} else {
daytime.setSoTimeout(2000);
OutputStream out = daytime.getOutputStream();
PrintStream pout = new PrintStream(out);
pout.print(pesan);
out.flush();
out.close();
BufferedReader messageIn = new BufferedReader(new InputStreamReader(daytime.getInputStream()));
System.out.println("Respond : " + messageIn.readLine());
System.out.println("diterima");
}
daytime.close();
//}
} catch (IOException e) {
System.err.println("Error : " + e);
}
}
}
OutputStream out = daytime.getOutputStream();
PrintStream pout = new PrintStream(out);
pout.print(pesan);
out.flush();
out.close();
https://docs.oracle.com/javase/7/docs/api/java/net/Socket.html#getOutputStream()
Closing the returned OutputStream will close the associated socket.
Socket get closed in such situations:
when you close the socket,
when you close the input or the output socket stream,
when you close the object, which is directly or indirectly wrapping the input or the output socket stream, e.g. BufferedReader or Scanner.
Server Class
OutputStream out = nextClient.getOutputStream();
PrintStream pout = new PrintStream(out);
pout.print(messageOut);
out.flush();
out.close(); //Don't close this
Client Code :
OutputStream out = daytime.getOutputStream();
PrintStream pout = new PrintStream(out);
pout.print(pesan);
out.flush();
out.close(); //Don't close this
I want to implement any one sorting algorithm using TCP/UDP on Server application and Give Input On Client side and client should sorted output from server and display sorted on input side. Here, I have created program for multiplication of a number. I am not getting how to pass int array from client side and receive the same array. How can I do that.It would be a great help. Thank in advance.
Client.java
package sorting_app;
import java.io.BufferedReader;
import java.io.BufferedWriter;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.OutputStream;
import java.io.OutputStreamWriter;
import java.net.InetAddress;
import java.net.Socket;
public class Client
{
private static Socket socket;
public static void main(String args[])
{
try
{
String host = "localhost";
int port = 25000;
InetAddress address = InetAddress.getByName(host);
socket = new Socket(address, port);
//Send the message to the server
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);
//Get the return message from the server
InputStream is = socket.getInputStream();
InputStreamReader isr = new InputStreamReader(is);
BufferedReader br = new BufferedReader(isr);
String message = br.readLine();
System.out.println("Message received from the server : " +message);
}
catch (Exception exception)
{
exception.printStackTrace();
}
finally
{
//Closing the socket
try
{
socket.close();
}
catch(Exception e)
{
e.printStackTrace();
}
}
}
}
Server.java
import java.io.BufferedReader;
import java.io.BufferedWriter;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.OutputStream;
import java.io.OutputStreamWriter;
import java.net.ServerSocket;
import java.net.Socket;
public class Server
{
private static Socket socket;
public static void main(String[] args)
{
try
{
int port = 25000;
ServerSocket serverSocket = new ServerSocket(port);
System.out.println("Server Started and listening to the port 25000");
//Server is running always. This is done using this while(true) loop
while(true)
{
//Reading the message from the client
socket = serverSocket.accept();
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";
}
//Sending the response back to the client.
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();
}
}
catch (Exception e)
{
e.printStackTrace();
}
finally
{
try
{
socket.close();
}
catch(Exception e){}
}
}
}
BufferedReader and BufferedWriter are for character streams.
Consider using other ways, like ObjectInputStream and ObjectOutputStream.
(DataOutputStream / DataInputStream could be good too)
I have an android app which will send a string to a server using the following code:
package com.example.testapp;
import java.io.BufferedWriter;
import java.io.ByteArrayInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStreamWriter;
import java.io.PrintWriter;
import java.net.InetAddress;
import java.net.Socket;
import java.net.UnknownHostException;
import android.app.Activity;
import android.os.Bundle;
import android.view.View;
import android.widget.EditText;
public class MainActivity extends Activity {
private Socket socket;
private static final int SERVERPORT = 5000;
private static final String SERVER_IP = "192.168.1.125";
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
new Thread(new ClientThread()).start();
}
public void onClick(View view) {
try {
EditText et = (EditText) findViewById(R.id.EditText01);
String str = et.getText().toString();
PrintWriter out = new PrintWriter(new BufferedWriter(
new OutputStreamWriter(socket.getOutputStream())),
true);
out.println(str);
} catch (UnknownHostException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
} catch (Exception e) {
e.printStackTrace();
}
}
class ClientThread implements Runnable {
#Override
public void run() {
try {
InetAddress serverAddr = InetAddress.getByName(SERVER_IP);
socket = new Socket(serverAddr, SERVERPORT);
} catch (UnknownHostException e1) {
e1.printStackTrace();
} catch (IOException e1) {
e1.printStackTrace();
}
}
}
}
In server side I am running a java program like the follows:
import java.io.IOException;
import java.io.ObjectInputStream;
import java.io.ObjectOutputStream;
import java.lang.ClassNotFoundException;
import java.net.ServerSocket;
import java.net.Socket;
public class SocketServerExample {
//static ServerSocket variable
private static ServerSocket server;
//socket server port on which it will listen
private static int port = 5000;
public static void main(String args[]) throws IOException, ClassNotFoundException{
//create the socket server object
server = new ServerSocket(port);
//keep listens indefinitely until receives 'exit' call or program terminates
while(true){
System.out.println("Waiting for client request");
//creating socket and waiting for client connection
Socket socket = server.accept();
//read from socket to ObjectInputStream object
ObjectInputStream ois = new ObjectInputStream(socket.getInputStream());
//convert ObjectInputStream object to String
String message = (String) ois.readObject();
System.out.println("Message Received: " + message);
//create ObjectOutputStream object
ObjectOutputStream oos = new ObjectOutputStream(socket.getOutputStream());
//write object to Socket
oos.writeObject("Hi Client "+message);
//close resources
ois.close();
oos.close();
socket.close();
//terminate the server if client sends exit request
if(message.equalsIgnoreCase("exit")) break;
}
System.out.println("Shutting down Socket server!!");
//close the ServerSocket object
server.close();
}
}
But it is not reading the String which I send from the android app. Instead when I submit from app, the java program shows the following errors:
Exception in thread "main" java.io.StreamCorruptedException: invalid stream header: 54657374
at java.io.ObjectInputStream.readStreamHeader(ObjectInputStream.java:803)
at java.io.ObjectInputStream.<init>(ObjectInputStream.java:298)
at SocketServerExample.main(SocketServerExample.java:29)
How can I fix this. Where is my error lays?? Is it on Server side or client side?? Please help me guys.
PROBLEM ANALYSIS:
You use a PrintWriter for sending from the client, but you use an ObjectInputStream on the receiving side of the server. These two are not compatible.
You have to use a pair of Writer and Reader together or a pair of ObjectOutputStream and ObjectInputStream, but you can't mix them.
SOLUTION:
We're going to use pairs of Writer and Reader. The client side already uses a Writer and a Reader, so we only need to change the server side.
On the server side, instead of the ObjectInputStream, use a BufferedReader:
BufferedReader reader = new BufferedReader(new InputStreamReader(socket.getInputStream()));
reader.readLine();
Moreover, use a PrintWriter instead of the ObjectOutputStream on the server side for sending back to the client:
PrintWriter writer = new PrintWriter(new BufferedWriter(
new OutputStreamWriter(socket.getOutputStream())),
true);
writer.println(str);
Alltogether, then the server side looks like this:
import java.io.IOException;
import java.io.BufferedWriter;
import java.io.BufferedReader;
import java.io.OutputStreamWriter;
import java.io.InputStreamReader;
import java.io.PrintWriter;
import java.lang.ClassNotFoundException;
import java.net.ServerSocket;
import java.net.Socket;
public class SocketServerExample {
//static ServerSocket variable
private static ServerSocket server;
//socket server port on which it will listen
private static int port = 5000;
public static void main(String args[]) throws IOException, ClassNotFoundException{
//create the socket server object
server = new ServerSocket(port);
//keep listens indefinitely until receives 'exit' call or program terminates
while(true){
System.out.println("Waiting for client request");
//creating socket and waiting for client connection
Socket socket = server.accept();
// //read from socket to ObjectInputStream object
// ObjectInputStream ois = new ObjectInputStream(socket.getInputStream());
// //convert ObjectInputStream object to String
// String message = (String) ois.readObject();
// System.out.println("Message Received: " + message);
BufferedReader reader = new BufferedReader(new InputStreamReader(socket.getInputStream()));
String message = reader.readLine();
System.out.println("Message Received: " + message);
// //create ObjectOutputStream object
// ObjectOutputStream oos = new ObjectOutputStream(socket.getOutputStream());
// //write object to Socket
// oos.writeObject("Hi Client "+message);
PrintWriter writer = new PrintWriter(new BufferedWriter(
new OutputStreamWriter(socket.getOutputStream())),
true);
writer.println("Hi Client "+message);
//close resources
reader.close();
writer.close();
socket.close();
//terminate the server if client sends exit request
if(message.equalsIgnoreCase("exit")) break;
}
System.out.println("Shutting down Socket server!!");
//close the ServerSocket object
server.close();
}
}
Use this on the client:
PrintWriter out = new PrintWriter(socket.getOutputStream(), true);
Use this on the server:
BufferedReader is = new BufferedReader(new InputStreamReader(clientSocket.getInputStream()));
String message = is.readLine();
Use flush() after sending anything.
out.println(str);
out.flush();