Multi-threaded Server Client Address already in use - java

What I'm trying to do is make receiver class in the server which receives the sent messages from the client and make a sender class in the client. I'm trying to make the receiver in the server first 'cause I'll probably figure out how to do that in the client side after learning it. But doing this gives me java.net.BindException: Address already in use: JVM_Bind. I think it's because I have another Server server = new Server(); in the receiver. How do I solve this?
Server.java
package MultithreadingServerClient;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.PrintWriter;
import java.net.ServerSocket;
import java.net.Socket;
import java.util.Scanner;
public class Server {
ServerSocket serverSocket = new ServerSocket(3000);
Socket socket = serverSocket.accept();
BufferedReader bufferedReader = new BufferedReader(new InputStreamReader(socket.getInputStream()));
PrintWriter printWriter = new PrintWriter(socket.getOutputStream(), true);
public Server() throws IOException {
}
public static void main(String[] args) {
Thread serverSender = new Thread(new ServerSender());
Thread serverReceiver = new Thread(new ServerReceiver());
serverSender.start();
serverReceiver.start();
}
}
// Sender class
class ServerSender implements Runnable {
#Override
public void run() {
try {
Server serve = new Server();
Scanner scanner = new Scanner(System.in);
String msg = "";
while (!msg.equalsIgnoreCase("exit")) {
System.out.print("Server: ");
msg = scanner.nextLine();
serve.printWriter.println(msg);
}
} catch (IOException e) {
System.err.println("Sender Error " + e);
}
}
}
class ServerReceiver implements Runnable {
#Override
public void run() {
try {
Server server = new Server();
System.out.println(server.bufferedReader.readLine());
} catch (IOException e) {
System.err.println("Receiver Error " + e);
}
}
}
Client.java
package MultithreadingServerClient;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.PrintWriter;
import java.net.Socket;
public class Client {
Socket socket = new Socket("localhost", 3000);
BufferedReader bufferedReader = new BufferedReader(new InputStreamReader(socket.getInputStream()));
PrintWriter printWriter = new PrintWriter(socket.getOutputStream());
public Client() throws IOException {
}
// Receive messages
public static void main(String[] args) {
try {
Client client = new Client();
while (true) {
System.out.println("Server: " + client.bufferedReader.readLine());
}
} catch (IOException e) {
System.out.println("Server Closed!");
}
}
}
class ClientSender implements Runnable {
#Override
public void run() {
try {
Client client = new Client();
client.printWriter.println("Test message: send to Server");
} catch (IOException e) {
e.printStackTrace();
}
}
}

Don't create multiple instances of Server, you may create the instance in main then just pass the bufferedReader to the receiver class, and the printWriter to the sender class.
Sender class :
class ServerSender implements Runnable {
private PrintWriter writer;
public ServerSender(PrintWriter printWriter){
writer = printWriter;
}
#Override
public void run() {
try {
Scanner scanner = new Scanner(System.in);
String msg = "";
while (!msg.equalsIgnoreCase("exit")) {
System.out.print("Server: ");
msg = scanner.nextLine();
writer.println(msg);
}
} catch (IOException e) {
System.err.println("Sender Error " + e);
}
}
}
Receiver class :
class ServerReceiver implements Runnable {
private BufferedReader reader;
public ServerReceiver(BufferedReader bufferedReader){
reader = bufferedReader;
}
#Override
public void run() {
try {
System.out.println(reader.readLine());
} catch (IOException e) {
System.err.println("Receiver Error " + e);
}
}
}
Method main in Server :
public static void main(String[] args) {
Server serve = new Server();
Thread serverSender = new Thread(new ServerSender(serve.printWriter));
Thread serverReceiver = new Thread(new ServerReceiver(serve.bufferedReader));
serverSender.start();
serverReceiver.start();
}

You have two threads starting a new instance of the connection at the same port (3000). I assume that you are trying to have one thread receive a message from a server and another one for sending a message to client. I don't think you need to have a design like this. This can be done in a single threaded environment. There is no need for client (sender & receiver) and server (sender & receiver).
ServerSocket.accept(); method will listen to all the message incoming to the specified port number.
In order for the server to send reply to the client . You can use
DataOutputStream.writeUTF() & DataOutputStream.flush() method.
The same goes for client side. Have a look at the program below.
class Server {
public static void main(String args[]) throws IOException {
try (ServerSocket serverSocket = new ServerSocket(3333); // open connection at port 3333
Socket socket = serverSocket.accept();
DataInputStream inputStream = new DataInputStream(socket.getInputStream());) {
DataOutputStream outStream = new DataOutputStream(socket.getOutputStream());
BufferedReader reader = new BufferedReader(new InputStreamReader(System.in));
String messageFromClient = "", messageToBeClient = "";
while (!messageFromClient.equals("exit")) {
messageFromClient = inputStream.readUTF();
System.out.println("Message From Client : " + messageFromClient);
messageToBeClient = reader.readLine();
outStream.writeUTF(messageToBeClient);
outStream.flush();
}
}
}
}
class Client {
public static void main(String args[]) throws Exception {
try (Socket socket = new Socket("localhost", 3333); // establish connection to the open socket at port 3333
DataInputStream inputStream = new DataInputStream(socket.getInputStream());) {
DataOutputStream outStream = new DataOutputStream(socket.getOutputStream());
BufferedReader reader = new BufferedReader(new InputStreamReader(System.in));
String messageFromServer = "", messageToServer = "";
while (!messageToServer.equals("exit")) {
messageToServer = reader.readLine();
outStream.writeUTF(messageToServer);
outStream.flush();
messageFromServer = inputStream.readUTF();
System.out.println("Message From Server : " + messageFromServer);
}
}
}
}

Related

Java Concurrent Socket Programming

Below is my code for a simple Concurrent Server. Whenever I run multiple clients, the server only prints out the input of the first client. I'm not sure what I've done wrong. Any help would be appreciated.
public static void main(String[] args) {
try {
ServerSocket serverSocket = new ServerSocket(8001);
while (true){
Socket clientSocket = serverSocket.accept();
System.out.println(clientSocket);
ConcurrentServer client = new ConcurrentServer(clientSocket);
client.start();
}
} catch (IOException i){}
}
public void run(){
try {
inputStream = new BufferedReader(new InputStreamReader(concurrentSocket.getInputStream()));
outputStream = new PrintWriter(new OutputStreamWriter(concurrentSocket.getOutputStream()));
String testString = inputStream.readLine();
System.out.println(testString);
} catch (IOException i){}
}
This code might help you to understand how to run multiple clients concurrently. :)
What this code does? TCP Client sends a string to the server and TCP server sends back the string in UPPERCASE format & the server can do this concurrently with multiple connections.
I have included 3 files for the server and one more for testing the server with multiple clients(ClientTest.java)
Main.java
import java.io.IOException;
public class Main {
public static void main(String[] args) {
try {
new Server(3000).start();
} catch (IOException e) {
e.printStackTrace();
}
}
}
Server.java
import java.io.IOException;
import java.net.ServerSocket;
import java.net.Socket;
import java.util.logging.Logger;
public class Server {
private ServerSocket sSocket;
private boolean run;
private int port;
public Server(int port) throws IOException {
this.port = port;
this.sSocket = new ServerSocket(this.port);
}
public void start() {
this.run = true;
Logger.getLogger(getClass().getName()).info("Server is listening on port: " + port);
try {
while (run) {
Socket cs = sSocket.accept();
Logger.getLogger(getClass().getName())
.info("New Client Connected! " + cs.getPort());
new Thread(new Client(cs)).start(); // Put to a new thread.
}
} catch (IOException e) {
Logger.getLogger(getClass().getName()).severe(e.getMessage());
}
}
public void stop() {
this.run = false;
}
}
Client.java (Client Process on server)
import java.io.*;
import java.net.Socket;
import java.util.logging.Logger;
public class Client implements Runnable {
private Socket clientSocket;
private DataOutputStream out; // write for the client
private BufferedReader in; // read from the client
public Client(Socket clientSocket) {
this.clientSocket = clientSocket;
}
#Override
public void run() {
// Do client process
outToClient(inFromClient().toUpperCase());
closeConnection();
}
private String inFromClient() {
String messageFromClient = "";
/*
* Do not use try with resources because once -
* - it exits the block it will close your client socket too.
*/
try {
in = new BufferedReader(new InputStreamReader(clientSocket.getInputStream()));
messageFromClient = in.readLine();
} catch (IOException e) {
Logger.getLogger(getClass().getName()).severe("InFromClientErr - " + e.getMessage());
}
return messageFromClient.trim().equals("") ? "No Inputs given!" : messageFromClient;
}
private void outToClient(String message) {
try {
out = new DataOutputStream(clientSocket.getOutputStream());
out.writeBytes(message);
} catch (IOException e) {
Logger.getLogger(getClass().getName()).severe("OutToClientErr - " + e.getMessage());
}
}
private void closeConnection() {
try {
in.close();
out.close();
clientSocket.close();
} catch (NullPointerException | IOException e) {
Logger.getLogger(getClass().getName()).severe(e.getMessage());
}
}
}
ClientTest.java (For Testing clients)
import java.io.*;
import java.net.Socket;
import java.util.Scanner;
public class ClientTest {
public static void main(String[] args) {
Socket clientSocket;
try {
clientSocket = new Socket("localhost", 3000);
DataOutputStream outToServer = new DataOutputStream(clientSocket.getOutputStream());
BufferedReader inFromServer = new BufferedReader(new InputStreamReader(clientSocket.getInputStream()));
outToServer.writeBytes(new Scanner(System.in).nextLine() + '\n'); // Get user input and send.
System.out.println(inFromServer.readLine()); // Print the server response.
} catch (IOException e) {
e.printStackTrace();
}
}
}
The issue was instead with the client. Not the server. The socket was declared outside of the for loop, and therefore only one connection was being created. Like so below:
public static void main(String[] args) {
try {
socket = new Socket("127.0.0.1", 8001);
for (int i = 0; i < 5; i++){
System.out.println("Starting client: " + i);
ConcurrentClient concurrentClient = new ConcurrentClient(socket, i);
concurrentClient.run();
}
} catch (IOException io) {
}
}
The Socket should be declared inside the for loop like so:
public static void main(String[] args) {
try {
for (int i = 0; i < 5; i++){
socket = new Socket("127.0.0.1", 8001);
System.out.println("Starting client: " + i);
ConcurrentClient concurrentClient = new ConcurrentClient(socket, i);
concurrentClient.run();
}
} catch (IOException io) {
}
}
I really don't know why you need so complex structure of input and output streams. It is better to use Scanner that will wait for the new input.
Also you can use PrintWriter to output the results of your conversation.
Here is server that accepts multiple clients:
import java.io.*;
import java.net.ServerSocket;
import java.net.Socket;
import java.util.Scanner;
public class ConcurrentServer extends Thread {
private Socket concurrentSocket;
public ConcurrentServer(Socket clientSocket) {
this.concurrentSocket = clientSocket;
}
public static void main(String[] args) {
try {
ServerSocket serverSocket = new ServerSocket(8001);
while (true){
Socket clientSocket = serverSocket.accept();
System.out.println(clientSocket);
ConcurrentServer client = new ConcurrentServer(clientSocket);
client.start();
}
} catch (IOException i){}
}
public void run(){
try {
InputStream inputStream = concurrentSocket.getInputStream();
Scanner scanner = new Scanner(inputStream);
OutputStream outputStream = concurrentSocket.getOutputStream();
PrintWriter pw = new PrintWriter(outputStream);
while(scanner.hasNextLine()){
String line = scanner.nextLine();
System.out.println(line);
pw.println("message: " + line);
pw.flush();
}
} catch (IOException i){}
}
}

How can the client and server pause to wait for the other to send the next message? [duplicate]

This question already has answers here:
Java Socket why server can not reply client
(4 answers)
Closed 3 years ago.
I am building a java client and server that plays a guess my number game. The server tells the client the range of numbers, the client enters a guess, and the server returns "Try Again" or the number if the client guessed the correct number. The server also needs to be multithreaded.
I have up to the part where the server sends the range but I cannot get the server and the client to pause at the points indicated by the comments in Client.java and in WorkerRunnable.java. I need the server and client to pause at this point so that it will wait to receive the message from the corresponding sender.
import java.net.ServerSocket;
import java.net.Socket;
import java.io.IOException;
public class GameServer implements Runnable{
public int serverPort = 8080;
public ServerSocket serverSocket = null;
public boolean isStopped = false;
public Thread runningThread = null;
public GameServer() {
this.serverPort = 8080;
}
public GameServer(int port) {
this.serverPort = port;
}
public void run() {
synchronized(this) {
this.runningThread = Thread.currentThread();
}
openServerSocket();
while(!this.isStopped) {
Socket clientSocket = null;
try {
clientSocket = this.serverSocket.accept();
}catch (IOException e) {
if(this.isStopped) {
System.out.println("The server has been stopped.");
return;
}
}
new Thread(new WorkerRunnable(clientSocket, "Oi m8")).start();
}
System.out.println("The server has been stopped.");
}
public synchronized void stop() {
this.isStopped = true;
try {
this.serverSocket.close();
}catch (IOException e) {
System.out.println("Error closing server.");
}
}
private void openServerSocket() {
try {
this.serverSocket = new ServerSocket(this.serverPort);
}catch (IOException e) {
System.out.println("Error opening server.");
}
}
}
public class Server {
public static void main(String [] args) {
GameServer server = new GameServer(9000);
new Thread(server).start();
System.out.println("The Server has started.");
}
}
import java.io.*;
import java.net.*;
public class Client {
public static void main(String [] args) throws IOException{
Socket clientSocket = new Socket("localhost", 9000);
BufferedReader inFromUser = new BufferedReader(new InputStreamReader(System.in));
BufferedReader inFromServer = new BufferedReader(new InputStreamReader(clientSocket.getInputStream()));
DataOutputStream outToServer = new DataOutputStream(clientSocket.getOutputStream());
String serverMessage;
String clientMessage;
serverMessage = inFromServer.readLine();
System.out.println(serverMessage);
System.out.print("Enter a number: ");
String num = inFromUser.readLine();
//I need for the client to wait here as well.
System.out.println("ugh");
}
}
import java.net.*;
import java.io.*;
import java.util.*;
public class WorkerRunnable implements Runnable{
public Socket clientSocket = null;
public String serverText = null;
public int number = -1;
public int guessCount = 0;
public WorkerRunnable(Socket clientSocket, String serverText) {
this.clientSocket = clientSocket;
this.serverText = serverText;
this.guessCount = 0;
}
public void run() {
try {
BufferedReader inFromClient = new BufferedReader(new InputStreamReader(clientSocket.getInputStream()));
OutputStream output = clientSocket.getOutputStream();
Random rand = new Random();
number = rand.nextInt(10);
output.write(("Guess an integer between 0 and 10." + number).getBytes());
//I need for the server to wait here
output.close();
}catch (IOException e) {
System.out.println("Something went wrong.");
}
}
}
Your problem is that you are reading lines but you aren't writing lines. You need to add a line terminator to the messages.
It has nothing to do with your title or what you're asking for in the body of your question, which don't agree with each other anyway. The reads will block until data arrives. In this case readLine() will block until a line terminator or end of stream arrives.

Socket in multithreading "deadlocked" Java

I am trying to launch server and client thread on the same process, but seems like the server thread is blocking the client thread (or vice versa). I'm not allowed to use any global variable between those threads(like semaphore or mutex, since the client and the server thread are launched by upper-class that I don't have the access of).
I found a similar question here , but it still use two different process (two main function).
Here is a sample of my code
The server code:
public class MyServer implements Runnable{
ServerSocket server;
Socket client;
PrintWriter out;
BufferedReader in;
public MyServer() throws IOException{
server = new ServerSocket(15243, 0, InetAddress.getByName("localhost"));
}
#Override
public void run() {
while(true){
try {
ArrayList<String> toSend = new ArrayList<String>();
System.out.println("I'll wait for the client");
client = server.accept();
out = new PrintWriter(client.getOutputStream(), true);
in = new BufferedReader(new InputStreamReader(client.getInputStream()));
String inputLine;
while((inputLine = in.readLine()) != null){
toSend.add("answering : "+inputLine);
}
for(String resp : toSend){
out.println(resp);
}
client.close();
out.close();
in.close();
} catch (IOException ex) {
}
}
}
}
And the client code:
public class MyClient implements Runnable{
Socket socket;
PrintWriter out;
BufferedReader in;
public MyClient(){
}
#Override
public void run() {
int nbrTry = 0;
while(true){
try {
System.out.println("try number "+nbrTry);
socket = new Socket(InetAddress.getByName("localhost"), 15243);
out = new PrintWriter(socket.getOutputStream(), true);
in = new BufferedReader(new InputStreamReader(socket.getInputStream()));
out.println("Hello "+nbrTry+" !! ");
String inputLine;
while((inputLine = in.readLine()) != null){
System.out.println(inputLine);
}
nbrTry++;
} catch (UnknownHostException ex) {
} catch (IOException ex) {
}
}
}
}
And the supposed upper-class launching those thread:
public class TestIt {
public static void main(String[] argv) throws IOException{
MyServer server = new MyServer();
MyClient client = new MyClient();
(new Thread(server)).start();
(new Thread(client)).start();
}
}
It gives me as output:
I'll wait for the client
Try number 0
And it stuck here. What should I do to keep both server and client code running?
Thank you.
I'll be willing to take up your questions but basically you need to think through your logic a bit more carefully.
MyServer.java
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.PrintWriter;
import java.net.InetAddress;
import java.net.ServerSocket;
import java.net.Socket;
public class MyServer implements Runnable {
ServerSocket server;
public MyServer() throws IOException {
server = new ServerSocket(15243, 0, InetAddress.getByName("localhost"));
}
#Override
public void run() {
while (true) {
try {
// Get a client.
Socket client = server.accept();
// Write to client to tell him you are waiting.
PrintWriter out = new PrintWriter(client.getOutputStream(), true);
out.println("[Server] I'll wait for the client");
// Let user know something is happening.
System.out.println("[Server] I'll wait for the client");
// Read from client.
BufferedReader in = new BufferedReader(new InputStreamReader(client.getInputStream()));
String inputLine = in.readLine();
// Write answer back to client.
out.println("[Server] Answering : " + inputLine);
// Let user know what it sent to client.
System.out.println("[Server] Answering : " + inputLine);
in.close();
out.close();
client.close();
} catch (Exception e) {
}
}
}
}
MyClient.java
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.PrintWriter;
import java.net.InetAddress;
import java.net.Socket;
import java.net.UnknownHostException;
public class MyClient implements Runnable {
Socket socket;
PrintWriter out;
BufferedReader in;
public MyClient() throws UnknownHostException, IOException {
}
#Override
public void run() {
int nbrTry = 0;
while (true) {
try {
// Get a socket
socket = new Socket(InetAddress.getByName("localhost"), 15243);
// Wait till you can read from socket.
in = new BufferedReader(new InputStreamReader(socket.getInputStream()));
String inputLine = in.readLine();
//inputLine contains the text '[Server] I'll wait for the client'. means that server is waiting for us and we should respond.
// Write to socket
out = new PrintWriter(socket.getOutputStream(), true);
out.println("[Client] Hello " + nbrTry + " !! ");
// Let user know you wrote to socket
System.out.println("[Client] Hello " + nbrTry++ + " !! ");
} catch (UnknownHostException ex) {
} catch (IOException ex) {
}
}
}
}
TestIt.java
import java.io.IOException;
public class TestIt {
public static void main(String[] argv) throws IOException {
MyServer server = new MyServer();
MyClient client = new MyClient();
(new Thread(server)).start();
(new Thread(client)).start();
}
}
Your client sends a string, then reads until the stream is exhausted:
while((inputLine = in.readLine()) != null){
BufferedReader.readLine() only returns null at the end of the stream, as I recall. On a stream, it will block until input is available
Your server receives until the stream is exhausted, then sends back its response.
After sending one line, you now have:
Your client waiting for a response.
Your server still waiting for more data from the client. But it doesn't send anything back until the end of the stream from the client (which never happens because the client is waiting for your response).

How can I get this code (from Java tutorial on sockets) to run?

I've just started with this section of the tutorial. I only have a basic understanding of what ports are, etc.
I tried to run this code:
import java.io.*;
import java.net.*;
public class EchoClient {
public static void main(String[] args) throws IOException {
Socket echoSocket = null;
PrintWriter out = null;
BufferedReader in = null;
try {
echoSocket = new Socket("taranis", 7);
out = new PrintWriter(echoSocket.getOutputStream(), true);
in = new BufferedReader(new InputStreamReader(
echoSocket.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 userInput;
while ((userInput = stdIn.readLine()) != null) {
out.println(userInput);
System.out.println("echo: " + in.readLine());
}
out.close();
in.close();
stdIn.close();
echoSocket.close();
}
}
"Don't know about host: taranis.
Java Result: 1"
Is the error catch I get. From my limited understanding; is the echo-server something which exists on my machine? If that's the case, what do I need to do to get this running? Or am I way off?
Also why have they chosen "taranis" as a parameter?
Ive also replaced "taranis" with "localhost" to see what happened.
It ended up catching an IOException this time.
EDIT: So I've found that the echo server is disabled by default in win7 and have activated it. However I cant even connect to it on telnet. I think I may just be in over my head. I've also tried the sockets you have recommended with no success.
From the same tutorial:
... The Socket constructor used here requires the name of the machine and the port number to which you want to connect. The example program uses the host name taranis. This is the name of a hypothetical machine on our local network. When you type in and run this program on your machine, change the host name to the name of a machine on your network. Make sure that the name you use is the fully qualified IP name of the machine to which you want to connect. The second argument is the port number. Port number 7 is the port on which the Echo server listens.`
In any case, you will probably want to change taranis to "localhost" and make sure an echo service is running on your machine. If it's not, you could use something like the following code to simulate an echo server.
import java.net.Socket;
import java.util.Formatter;
import java.util.Scanner;
import java.io.IOException;
import java.net.ServerSocket;
import java.util.ArrayList;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
public class EchoServer {
public static void main(String[] args) {
try {
new EchoServer(INSERTPORT).execute();
} catch (IOException e) {
e.printStackTrace();
System.exit(1);
}
}
private ServerSocket serverSocket;
private int port;
private ArrayList<Client> clientList;
private ExecutorService clientRunner;
public EchoServer(int port) throws IOException {
this.port = port;
serverSocket = new ServerSocket(port);
clientRunner = Executors.newCachedThreadPool();
clientList = new ArrayList<>();
}
public void sendMessageToAll(String message) {
for (Client c : clientList) {
c.displayMessage(message);
}
}
public void execute() throws IOException {
while (true) {
clientList.add(new Client(serverSocket.accept(), this));
clientRunner.execute(clientList.get(clientList.size()-1));
}
}
private class Client implements Runnable {
private Socket clientSocket;
private Scanner input;
private Formatter output;
public Client(Socket s) throws IOException {
clientSocket = s;
input = new Scanner(clientSocket.getInputStream());
output = new Formatter(clientSocket.getOutputStream());
}
public void displayMessage(String s) {
output.format(s + "\n");
output.flush();
}
#Override
public void run() {
while(clientSocket.isConnected()) {
if(input.hasNextLine()) {
sendMessageToAll(input.nextLine());
}
}
}
}
}
Edit: Just for completeness, as you mentioned some problems running the code, you run the server (this code) and leave it running in the background, then run the client (the code you posted). I tested it, works fine.
Try this,
Use the loopback address of 127.0.0.1 instead of taranis.
Use port higher than 1024, something like 4444, 8333 etc....
I am also adding my code that i used to learn Client Server Commnu
Client Side Code:
public class ClientWala {
public static void main(String[] args) throws Exception{
Boolean b = true;
Socket s = new Socket("127.0.0.1", 4444);
System.out.println("connected: "+s.isConnected());
OutputStream output = s.getOutputStream();
PrintWriter pw = new PrintWriter(output,true);
// to write data to server
while(b){
if (!b){
System.exit(0);
}
else {
pw.write(new Scanner(System.in).nextLine());
}
}
// to read data from server
InputStream input = s.getInputStream();
InputStreamReader isr = new InputStreamReader(input);
BufferedReader br = new BufferedReader(isr);
String data = null;
while ((data = br.readLine())!=null){
// Print it using sysout, or do whatever you want with the incoming data from server
}
}
}
Server Side Code:
public class ServerTest {
ServerSocket s;
public void go() {
try {
s = new ServerSocket(44457);
while (true) {
Socket incoming = s.accept();
Thread t = new Thread(new MyCon(incoming));
t.start();
}
} catch (IOException e) {
e.printStackTrace();
}
}
class MyCon implements Runnable {
Socket incoming;
public MyCon(Socket incoming) {
this.incoming = incoming;
}
#Override
public void run() {
try {
PrintWriter pw = new PrintWriter(incoming.getOutputStream(),
true);
InputStreamReader isr = new InputStreamReader(
incoming.getInputStream());
BufferedReader br = new BufferedReader(isr);
String inp = null;
boolean isDone = true;
System.out.println("TYPE : BYE");
System.out.println();
while (isDone && ((inp = br.readLine()) != null)) {
System.out.println(inp);
if (inp.trim().equals("BYE")) {
System.out
.println("THANKS FOR CONNECTING...Bye for now");
isDone = false;
s.close();
}
}
} catch (IOException e) {
// TODO Auto-generated catch block
try {
s.close();
} catch (IOException e1) {
// TODO Auto-generated catch block
e1.printStackTrace();
}
e.printStackTrace();
}
}
}
public static void main(String[] args) {
new ServerTest().go();
}
}

java.io.StreamCorruptedException: invalid stream header: 72657175

Hey I am implementing an electronic voting system based on client server chat.
When I run the server it runs without any problems but without printing as well and also the client. But as soon as I give the input to the client, it gives me the following exception and crashes. Here is the code of the server and the client. So what do u think I should do to start the engine?
package engine;
import java.io.*;
import java.net.*;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.Collections;
import java.util.GregorianCalendar;
public class Server {
ServerSocket server;
int port = 6000;
public Server() {
try {
server = new ServerSocket(6000);
} catch (IOException e) {
e.printStackTrace();
}
}
public void handleConnection(){
try {
while(true){
Socket connectionSocket;
connectionSocket = server.accept();
new ConnectionHandler(connectionSocket);
}
} catch (IOException e) {
e.printStackTrace();
}
}
public static void main(String[] args) {
Server server = new Server();
server.handleConnection();
}
}
class ConnectionHandler implements Runnable {
Socket connectionSocket;
Calendar votingStartTime;
Calendar votingEndTime;
boolean timeUp;
ObjectInputStream inFromClient;
ObjectOutputStream outToClient;
BufferedWriter outToFile;
BufferedReader inFromAdmin;
ArrayList<SingleClient> clients = new ArrayList<SingleClient>();
ArrayList<Candidate> candidates;
this is the part of the code the Exception comes from:
public ConnectionHandler(Socket socket) {
try {
this.connectionSocket = socket;
votingStartTime = new GregorianCalendar();
outToClient = new ObjectOutputStream(
connectionSocket.getOutputStream());
inFromClient = new ObjectInputStream(
connectionSocket.getInputStream());
inFromAdmin = new BufferedReader(new InputStreamReader(System.in));
startVotingSession();
Thread t = new Thread(this);
t.start();
} catch (IOException e) {
e.printStackTrace();
}
}
and this is the client's main method the Exception as soon as i give the input:
public static void main(String[] args) throws Exception {
client c = new client();
BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
String input;
while(true){
input = br.readLine();
if(input.equals("0")){
c.register();
}else if(input.equals("1")){
c.login();
}else if(input.equals("2")){
c.listCandidates();
}else if(input.equals("3")){
c.vote();
}else if(input.equals("4")){
c.checkResults();
}else if(input.equals("5")){
c.checkFinalResults();
}else if(input.equals("6")){
c.logout();
}else {
break;
}
}
}
}
without seeing the relevant code, i would guess you are recreating the ObjectInputStream on an existing socket InputStream. you must create the object streams once per socket and re-use them until you are completely finished with the socket connection. also, you should always flush the ObjectOutputStream immediately after creation to avoid deadlock.

Categories

Resources