I have been trying to play around with Java's Socket class and I have hit a tough spot. I have three classes: EchoServerTemplate, ConcurrentServer, and EchoClient.
I want to send a website(www.google.com) from a client to the server and then have the server return the IP address. I think I am extremely close, but I do not know how BufferedStreamer in Java works well enough to figure out the error messages.
Here is my code for all three classes:
EchoServerTemplate (This is where I want the Web Address to be translated):
import java.net.*;
import java.io.*;
public class EchoServerTemplate extends Thread
{
public static final int DEFAULT_PORT = 6007;
public static final int BUFFER_SIZE = 256;
Socket clientSocket;
EchoServerTemplate(Socket cs){
clientSocket = cs;
}
public void run(){
InputStream fromClient = null;
OutputStream toClient = null;
byte[] buffer = new byte[BUFFER_SIZE];
String printaddress = null;
try {
while(true){
PrintWriter pout = new PrintWriter(clientSocket.getOutputStream(), true);
fromClient = new BufferedInputStream(clientSocket.getInputStream());
try {
InetAddress address = InetAddress.getByName(fromClient.toString());
printaddress = address.toString();
}
catch(UnknownHostException e){
System.out.println(e);
}
toClient = new BufferedOutputStream(clientSocket.getOutputStream());
while (printaddress != null) {
toClient.write(printaddress.getBytes("UTF-8"));
toClient.flush();
printaddress = null;
}
fromClient.close();
toClient.close();
clientSocket.close();
}
}
catch (IOException ioe) {
ioe.printStackTrace();}
}
}
ConcurrentServer:
import java.io.*;
import java.net.*;
public class ConcurrentServer {
public static final int BUFFER_SIZE = 256;
public static void main(String[] args) throws IOException {
try {
int serverPortNumber = 6007;
ServerSocket sock = new ServerSocket(serverPortNumber);
while (true) {
Socket clientSocket = sock.accept();
EchoServerTemplate thread = new EchoServerTemplate(clientSocket);
thread.start();
}
}
catch (IOException ioe) {
ioe.printStackTrace();}
}
}
EchoClient:
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("127.0.0.1", 6007);
out = new PrintWriter(echoSocket.getOutputStream(), true);
in = new BufferedReader(new InputStreamReader(
echoSocket.getInputStream()));
} catch (UnknownHostException e) {
System.err.println("Don't know about host: ");
System.exit(1);
} catch (IOException e) {
System.err.println("Couldn't get I/O for "
+ "the connection to the host.");
System.exit(1);
}
BufferedReader stdIn = new BufferedReader(
new InputStreamReader(System.in));
String userInput;
while ((userInput = stdIn.readLine()) != null) {
out.println(userInput);
System.out.println("IP Address: " + in.readLine());
}
out.close();
in.close();
stdIn.close();
echoSocket.close();
}
}
The task I accomplished before this was just having the ConcurrentServer repeat what was typed on the client. In modifying the code I may have accidentally messed something up. Here are the error messages I am receiving:
run: www.google.com Exception in thread "main"
java.net.SocketException: Connection reset at
java.net.SocketInputStream.read(SocketInputStream.java:189) at
java.net.SocketInputStream.read(SocketInputStream.java:121) at
sun.nio.cs.StreamDecoder.readBytes(StreamDecoder.java:283) at
sun.nio.cs.StreamDecoder.implRead(StreamDecoder.java:325) at
sun.nio.cs.StreamDecoder.read(StreamDecoder.java:177) at
java.io.InputStreamReader.read(InputStreamReader.java:184) at
java.io.BufferedReader.fill(BufferedReader.java:154) at
java.io.BufferedReader.readLine(BufferedReader.java:317) at
java.io.BufferedReader.readLine(BufferedReader.java:382) at
EchoClient.main(EchoClient.java:31) Java Result: 1 BUILD SUCCESSFUL
(total time: 4 seconds)
Any help is appreciated. If you need any more information, please let me know.
Related
Closed. This question needs details or clarity. It is not currently accepting answers.
Want to improve this question? Add details and clarify the problem by editing this post.
Closed 10 months ago.
Improve this question
Here I can solve socket programming for chat application between multiple client and server where client can send multiple message to the server. But now I want to solve a new problem where conversion of any string from any client [each client can send at most 2 messages] into a FULL UPPERCASE string with the help of the server. The server will be able to serve at most 5 clients.
This is my client coe.....
import java.io.IOException;
import java.io.ObjectInputStream;
import java.io.ObjectOutputStream;
import java.net.Socket;
import java.util.Scanner;
public class Client {
public static void main(String[] args) throws IOException {
System.out.println("Client started..");
Socket socket = new Socket("127.0.0.1", 22222);
System.out.println("Client Connected..");
ObjectOutputStream oos = new ObjectOutputStream(socket.getOutputStream());
ObjectInputStream ois = new ObjectInputStream(socket.getInputStream());
while (true) {
Scanner sc = new Scanner(System.in);
String message = sc.nextLine();
if(message.equals("exit")){
break;
}
//sent to server...
oos.writeObject(message);
try {
//receive from server..
Object fromServer = ois.readObject();
System.out.println("From Server: " + (String) fromServer);
} catch (ClassNotFoundException e) {
e.printStackTrace();
}
}
socket.close();
}
}
This is my server code........
import java.io.IOException;
import java.io.ObjectInputStream;
import java.io.ObjectOutputStream;
import java.net.ServerSocket;
import java.net.Socket;
public class Server {
public static void main(String[] args) throws IOException {
ServerSocket serverSocket = new ServerSocket(22222);
System.out.println("Server Started..");
while (true) {
Socket socket = serverSocket.accept();
System.out.println("Client connected..");
// new Server Thread Start.....
new ServerThread(socket);
}
}
}
class ServerThread implements Runnable {
Socket clientSocket;
Thread t;
ServerThread(Socket clientSocket) {
this.clientSocket = clientSocket;
t = new Thread(this);
t.start();
}
#Override
public void run() {
try {
ObjectInputStream ois = new ObjectInputStream(clientSocket.getInputStream());
ObjectOutputStream oos = new ObjectOutputStream(clientSocket.getOutputStream());
while (true) {
//read from client...
Object cMsg = ois.readObject();
if (cMsg == null)
break;
System.out.println("From Client: " + (String) cMsg);
String serverMsg = (String) cMsg;
serverMsg = serverMsg.toUpperCase();
//send to client..
oos.writeObject(serverMsg);
}
} catch (ClassNotFoundException | IOException e) {
e.printStackTrace();
}
try {
clientSocket.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
// Sever side
package sockettreading;
import java.io.*;
import java.net.*;
/**
*
* #author Amanur Rahman
*/
public class SocketTreading {
public static void main(String[] args) throws IOException {
ServerSocket ss = new ServerSocket(5050);
System.out.println("Server is starting...");
int cn=1;
while (cn<=5) {
Socket s = ss.accept();
System.out.println("Client"+cn+" is connected \n" + s);
DataInputStream dis = new DataInputStream(s.getInputStream());
DataOutputStream dos = new DataOutputStream(s.getOutputStream());
System.out.println("Assinging new thread for this client");
Thread t = new ClientHandler(s, dis, dos);
t.start();
cn++;
}
System.out.println("Client limit cross");
ss.close();
}
}
class ClientHandler extends Thread {
final Socket soc;
final DataInputStream input;
final DataOutputStream output;
int i = 1;
public ClientHandler(Socket s, DataInputStream dis,
DataOutputStream dos) {
this.soc = s;
this.input = dis;
this.output = dos;
}
#Override
public void run() {
String received;
String ends;
String toreturn;
while (i <= 2) {
try {
output.writeUTF("Please write your message : ");
String str = input.readUTF();
System.out.println("Client msg is: "+ str.toUpperCase());
output.writeUTF("Do you want to exit or continue ( if exit type \"ENDS\" ) ");
ends = input.readUTF();
if (ends.equals("ENDS")) {
System.out.println("Client" + this.soc + "send exit.");
this.soc.close();
System.out.println("Connection closed");
break;
}
} catch (IOException e) {
System.out.println(e);
}
System.out.println("" + i);
i++;
}
try {
this.input.close();
this.output.close();
} catch (IOException e) {
System.out.println(e);
}
}
}
// client side
package sockettreading;
import java.io.*;
import java.net.Socket;
import java.util.Scanner;
/**
*
* #author Amanur Rahman
*/
public class ClientThreading {
public static void main(String[] args) throws IOException {
try(Socket s = new Socket("localhost", 5050);){
System.out.println("Connected");
Scanner scn = new Scanner(System.in);
DataOutputStream dos = new DataOutputStream(s.getOutputStream());
DataInputStream dis = new DataInputStream(s.getInputStream());
int i = 1;
while (i <= 2) {
System.out.println(dis.readUTF());
String num1 = scn.nextLine();
dos.writeUTF(num1);
System.out.println(dis.readUTF());
String num2 = scn.nextLine();
dos.writeUTF(num2);
System.out.println(dis.readUTF());
String ends = scn.nextLine();
dos.writeUTF(ends);
if (ends.equals("ENDS")) {
System.out.println("Closing the connection" + s);
s.close();
System.out.println("Connection closed");
break;
}
i++;
}
System.out.println(dis.readUTF());
s.close();
dos.close();
dis.close();
}
catch (IOException ex) {
if(ex.getMessage()!=null){
System.out.println("Already 5 clients are served so the server is closed: ");
}else{
System.out.println("Client 2 message already send. That's way the connection closed.");
}
}
}
}
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){}
}
}
I tried to send message from server to client but if i send message the client needs to connect again or println again...
So how does it work?
I tried to println again from server to client but the client wont receive it.
So how to send message to a specific client at any time.
Server:
package server.server.com;
import java.io.BufferedReader;
import java.io.BufferedWriter;
import java.io.ByteArrayInputStream;
import java.io.FileReader;
import java.io.FileWriter;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.OutputStream;
import java.io.PrintWriter;
import java.net.ServerSocket;
import java.net.Socket;
import java.nio.charset.Charset;
import java.util.ArrayList;
public class Server extends Thread {
private static ServerSocket serverSocket;
public static Socket clientSocket;
private static InputStreamReader inputStreamReader;
private static BufferedReader bufferedReader;
private static String message;
static InputStream is;
static OutputStream os;
static byte[] buf;
static BufferedReader reader;
static BufferedWriter writer;
static double ConsoleMessage;
public static String output;
static BufferedReader bufferedReader2;
public static void main(String[] args) {
try {
serverSocket = new ServerSocket(12345);
} catch (IOException e) {
System.out.println("Could not listen on port: 12345");
}
System.out.println("Server started. Listening to the port 12345");
while (true) {
try {
clientSocket = serverSocket.accept();
inputStreamReader = new InputStreamReader(
clientSocket.getInputStream());
bufferedReader = new BufferedReader(inputStreamReader);
PrintWriter out = new PrintWriter(
clientSocket.getOutputStream(), true);
InputStream inputStream = new ByteArrayInputStream(
bufferedReader.readLine().getBytes(
Charset.forName("UTF-8")));
bufferedReader2 = new BufferedReader(new InputStreamReader(
inputStream));
output = bufferedReader2.readLine();
System.out.println(output);
out.flush();
out.close();
inputStreamReader.close();
clientSocket.close();
} catch (IOException ex) {
System.out.println("Problem in message reading");
}
}
}
}
Client:
client = new Socket();
client.connect(
new InetSocketAddress(
"IP-ADDRESS",
PORT),
5000);
in = new BufferedReader(
new InputStreamReader(
client.getInputStream()));
printlng = new PrintWriter(
client.getOutputStream());
printlng.println(mLongitude);
printlng.flush();
try {
if ((Response = in
.readLine()) != null) {
....
You should take a look at http://developer.android.com/google/gcm/index.html. Maybe you could take advantage of push notifications in your app.
Maybe you can do something like this
Server:
private boolean sendMessage(final String msg, final String dstIp, final int dstPort) {
DatagramSocket sendSocket = null;
try {
sendSocket = new DatagramSocket();
final InetAddress local = InetAddress.getByName(dstIp);
final int msg_length = msg.length();
final byte[] message1 = msg.getBytes();
final DatagramPacket sendPacket = new DatagramPacket(message1,
msg_length, local, dstPort);
sendSocket.send(sendPacket);
} catch (final Exception e) {
e.printStackTrace();
return false;
} finally {
if (sendSocket != null) {
sendSocket.disconnect();
sendSocket.close();
sendSocket = null;
}
}
return true;
}
Client:
public static void receiveMessage() {
if ((socket == null) || socket.isClosed()) {
socket = new DatagramSocket(BROADCAST_PORT);
socket.setSoTimeout(5000);
}
try {
idMsgs.clear();
while ((socket != null) && !socket.isClosed()) {
socket.setReuseAddress(true);
socket.setSoTimeout(10000);
try {
final byte[] receiveBuffer = new byte[sizepck];
final DatagramPacket packet = new DatagramPacket(
receiveBuffer, receiveBuffer.length);
socket.receive(packet);
} catch (final SocketTimeoutException e) {
} catch (final Throwable e) {
}
}
} catch (final Throwable e1) {
try {
Thread.sleep(TIME_RETRY);
} catch (final InterruptedException e) {
e.printStackTrace();
}
}
finally {
if (socket != null) {
socket.close();
}
}
}
I have written a program where the client should be able to establish connection, and write to som message to the server. And the server should print this message.
The problem is that once the client connect to the server, I get an exception with the following message:
java.net.ConnectException: connect: Address is invalid on local machine, or port is not valid on remote machine
at java.net.PlainSocketImpl.socketConnect(Native Method)
at java.net.PlainSocketImpl.doConnect(PlainSocketImpl.java:351)
at java.net.PlainSocketImpl.connectToAddress(PlainSocketImpl.java:213)
at java.net.PlainSocketImpl.connect(PlainSocketImpl.java:200)
at java.net.SocksSocketImpl.connect(SocksSocketImpl.java:366)
at java.net.Socket.connect(Socket.java:529)
at java.net.Socket.connect(Socket.java:478)
at java.net.Socket.<init>(Socket.java:375)
at java.net.Socket.<init>(Socket.java:189)
at Client.<init>(Client.java:21)
at Server.startServer(Server.java:42)
at Server.main(Server.java:62)
My code for the server is as shown below:
import java.io.*;
import java.net.*;
public class Server {
private int port = 5555;
public void printServerAddress() {
InetAddress i = null;
String host = null;
try {
i = InetAddress.getLocalHost();
} catch (UnknownHostException e) {
e.printStackTrace();
}
host = i.getHostAddress();
System.out.println("Contact this server at address: " + host + " and port: " + port);
}
public void startServer() {
ServerSocket serverSocket = null;
BufferedReader reader = null;
Socket socket = null;
String fromClient = null;
try {
serverSocket = new ServerSocket(port);
while(true) {
socket = serverSocket.accept();
reader = new BufferedReader(new InputStreamReader(socket.getInputStream()));
if(socket != null) {
System.out.println("Connection from: " + socket);
}
Thread thread = new Thread(new Client(socket));
thread.start();
while((fromClient = reader.readLine()) != null) {
System.out.println("From client: " + fromClient);
}
reader.close();
socket.close();
}
} catch (IOException e) {
}
}
public static void main(String[] args) {
Server server = new Server();
server.printServerAddress();
server.startServer();
}
}
And the code for the client is:
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.PrintWriter;
import java.net.Socket;
import java.net.UnknownHostException;
import java.util.Scanner;
public class Client implements Runnable{
private int port;
private String serverAddress;
private PrintWriter writer;
private BufferedReader reader;
public Client(Socket socket)
{
try {
socket = new Socket(serverAddress, port);
writer = new PrintWriter(socket.getOutputStream(), true);
reader = new BufferedReader(new InputStreamReader(socket.getInputStream()));
} catch (UnknownHostException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
}
#Override
public void run() {
System.out.println("Write message to server:");
Scanner scanner = new Scanner(System.in);
while(scanner.next() != "quit") {
writeToServer(scanner.next());
}
writer.close();
}
public void writeToServer(String message) {
writer.write(message);
}
public void readFromServer() {
String msg = null;
try {
while((msg = reader.readLine()) != null) {
System.out.println("From server: " + msg);
}
reader.close();
} catch (IOException e) {
e.printStackTrace();
}
}
public static void main(String[] args) throws UnknownHostException, IOException {
Socket s = new Socket("localhost", 5555);
new Client(s);
}
}
Any idea on what I did wrong, and how to fix my problem?
socket = new Socket(serverAddress, port);
serverAddress is null and port is 0.
try to define the serverAddress variable and the port before call new Socket(serverAddress, port)
or change
socket = new Socket(serverAddress, port);
to
this.socket = socket;
edit
you can change your constructer to :
public Client(String serverAddress, int port)
{
try {
Socket socket = new Socket(serverAddress, port);
writer = new PrintWriter(socket.getOutputStream(), true);
reader = new BufferedReader(new InputStreamReader(socket.getInputStream()));
} catch (UnknownHostException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
}
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.