I'm making a simple java server & client for Educational purposes while finishing learning the Connections chapters in java language, and I had several problems while running the program, so i would be glad if I could get any kind of help to solve my problem, I had a main problems while running it
Problem : A text doesn't get sent both sides, I have made 2 clients, when I send text from client 1 for exemple to client 2, its all good, but vise-versa it doesn't
Sourse Code: main class
public class Start {
public static void main(String [] args) {
chatserver server = new chatserver();
server.go();
chatclient chat = new chatclient();
chat.go();
chatclient2 chat2 = new chatclient2();
chat2.go();
}
}
First Client class:
import java.io.*;
import java.net.*;
import java.util.*;
import javax.swing.*;
import java .awt.*;
import java.awt.event.*;
public class chatclient {
JTextArea incoming;
JTextField outgoing;
BufferedReader reader;
PrintWriter writer;
Socket sock;
public void go() {
JFrame frame = new JFrame("Simple Chat Client V.1");
JPanel mainPanel = new JPanel() ;
incoming = new JTextArea(15,50);
incoming.setLineWrap(true);
incoming.setWrapStyleWord(true) ;
incoming.setEditable(false);
JScrollPane qScroller = new JScrollPane(incoming) ;
qScroller.setVerticalScrollBarPolicy(ScrollPaneConstants.VERTICAL_SCROLLBAR_ALWAYS);
qScroller.setHorizontalScrollBarPolicy(ScrollPaneConstants.HORIZONTAL_SCROLLBAR_NEVER);
outgoing = new JTextField(30);
JButton sendButton = new JButton("Send");
sendButton.addActionListener(new sendz());
mainPanel.add (qScroller) ;
mainPanel.add(outgoing);
mainPanel.add(sendButton);
connectinsetup();
Thread thread = new Thread(new reader());
thread.start();
frame.getContentPane().add(BorderLayout.CENTER,mainPanel);
frame.setSize(500,500);
frame.setVisible(true);
}
public void connectinsetup() {
try{
Socket socket = new Socket("127.0.0.1",5000);
InputStreamReader stream = new InputStreamReader(socket.getInputStream());
reader = new BufferedReader(stream);
writer = new PrintWriter(socket.getOutputStream());
System.out.println("Connection Established");
}
catch(IOException ex) {
ex.printStackTrace();
}
}
public class sendz implements ActionListener {
public void actionPerformed(ActionEvent arg0) {
try{
writer.println(outgoing.getText());
writer.flush();
}
catch(Exception exz){
exz.printStackTrace();
}
outgoing.setText("");
outgoing.requestFocus();
}
}
public class reader implements Runnable{
public void run() {
String msg;
try{
while ( (msg = reader.readLine() ) != null) {
incoming.append(msg + "\n");
}
}
catch(Exception ex){
ex.printStackTrace();
}
}
}
}
Server Class:
import java.io.*;
import java.net.*;
public class chatserver {
PrintWriter writer;
public void go() {
try{
ServerSocket socket = new ServerSocket(5000);
while(true) {
Socket serversocket = socket.accept();
Thread thread = new Thread(new clienthandler(serversocket));
thread.start();
writer = new PrintWriter(serversocket.getOutputStream());
}
}
catch (Exception ex) {
ex.printStackTrace();
}
} // end go method
public class clienthandler implements Runnable {
Socket sock;
BufferedReader reader;
public clienthandler( Socket socks) {
try{
sock = socks;
InputStreamReader stream = new InputStreamReader(socks.getInputStream());
reader = new BufferedReader(stream);
}
catch(IOException ex) {
ex.printStackTrace();
}
}
public void run() {
String msg;
try{
while((msg = reader.readLine())!= null ) {
tellall(msg);
}
}
catch(Exception ex) {
ex.printStackTrace();
}
}
} //end clienthandler class
public void tellall(String text){
String msgall = text;
try{
writer.println(msgall);
writer.flush();
}
catch(Exception ex){
ex.printStackTrace();
}
} //end tellall method
}//end chatserver
And this is the Exceptions i get guys:
java.net.BindException: Address already in use: JVM_Bind
at java.net.DualStackPlainSocketImpl.bind0(Native Method)
at java.net.DualStackPlainSocketImpl.socketBind(Unknown Source)
at java.net.AbstractPlainSocketImpl.bind(Unknown Source)
at java.net.PlainSocketImpl.bind(Unknown Source)
at java.net.ServerSocket.bind(Unknown Source)
at java.net.ServerSocket.<init>(Unknown Source)
at java.net.ServerSocket.<init>(Unknown Source)
at test.chatserver.go(chatserver.java:12)
at test.Start.main(Start.java:12)
I hope to be helpful, I would say it has some bugs in your code such as:
chatclient chat = new chatclient();
chat.go();
chatclient2 chat2 = new chatclient2();
chat2.go();
You dont have any chatclient2, you should do:
chatclient chat = new chatclient();
chat.go();
chatclient chat2 = new chatclient();
chat2.go();
Otherwise, if you dont put the server in a different thread, the application will be frozen as it will be waiting for clients to connect (and the beginning of customers is below) is solved as easy as:
new Thread() {
public void run() {
chatserver server = new chatserver();
server.go();
}
}.start();
and in response to your question of why only text appears in one of the clients is because when you do on the server:
Socket serversocket = socket.accept();
Thread thread = new Thread(new clienthandler(serversocket));
thread.start();
writer = new PrintWriter(serversocket.getOutputStream());
each time a client connects, the 'writer' is overwritten with the last client socket (Each client has its own socket and with which we can communicate with he)
You can fix it doing for example an array of different writer with sockets ..
Greetings, I hope to be helpful = D
The BindException is thrown because the port is already in use.
There could be 2 reasons for that:
A Socket continues to run even when your program has already been terminated if you do not manually call .close().
The port is used by another service (for example web-server, database-server, ...)
I suspect option 1 is reason for your particular Exception. Just try another port or manually kill the java-background-task and then try running your program again (and close the sockets this time properly).
When to close the Sockets:
At first i would add a method shutdown() to both the client and the server. In these methods you just close all socket-instances you have, like for example here (you may need some catch-blocks though):
public void shutdown() {
serverSocket.close();
/* close other sockets here */
}
Then you add a WindowListener to both of the client-GUIs and do in windowClosing():
public void windowClosing(WindowEvent evt) {
client.shutdown();
}
For closing the server you could add the following code to the main-method:
System.out.println("Press Enter to stop the server ...");
System.in.read(); // wait for an "Enter"-press in the console
server.shutdown();
When closing a connected Socket, some Exceptions will probably be thrown on the other end of the connection. So don't forget to put appropriate catch-blocks there.
Related
Relevant code:
#Test
public void serverTest() throws IOException {
GameServer server = new GameServer();
server.start(9000);
GameClient client1 = new GameClient();
GameClient client2 = new GameClient();
client1.startConnection("localhost", 9000);
client2.startConnection("localhost", 9000);
client1.sendMessage("Hey I am client 1");
client2.sendMessage("Hey I am client 2");
}
public class GameServer {
private ServerSocket serverSocket;
public void start(int port) throws IOException {
System.out.println("Server started !!!");
serverSocket = new ServerSocket(port);
while (true) {
new Thread(new GameClientHandler(serverSocket.accept())).start();
}
}
public void stop() throws IOException {
serverSocket.close();
}
private static class GameClientHandler implements Runnable {
private Socket clientSocket;
private PrintWriter out;
private BufferedReader in;
public GameClientHandler(Socket socket) {
this.clientSocket = socket;
}
#Override
public void run() {
System.out.println(Thread.currentThread().getName());
try {
out = new PrintWriter(clientSocket.getOutputStream(), true);
in = new BufferedReader(new InputStreamReader(clientSocket.getInputStream()));
String inputLine = in.readLine();
while ((inputLine = in.readLine()) != null){
System.out.print(inputLine);
}
} catch (IOException e) {
e.printStackTrace();
}
try {
in.close();
out.close();
clientSocket.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
Why can't the server and client be started together in the #Test? I think it gets stuck in the infinite while loop but at the same time, shouldn't there be context switching with the new threads started after accepting the connection?
I expected at least the name of the 2 new threads to be printed but it doesn't happen.
Let us look carefully to your test code:
GameServer server = new GameServer();
Ok, this lines creates a server, and the test thread is ready to execute next line
server.start(9000);
Ok, the test thread starts the server, and will be ready to execute the next line when the start method will return.
What happens in start:
System.out.println("Server started !!!");
Ok, you should see that message
serverSocket = new ServerSocket(port);
Ok, you have created a ServerSocket
while (true) {
new Thread(new GameClientHandler(serverSocket.accept())).start();
}
ok you a waiting for a connection (at serverSocket.accept()), will create a new thread to handle it as soon as you will get one, and loop again.
But as this point, the test thread is waiting and will never go to the following line to start the first connection. And it will remain stuck unless something else (maybe another thread) starts those damned connections.
The method GameServer.start will only return with an exception. That is because you have the while-loop.
So your test execution will start the server and wait for someone to open a connection, but that never happens.
I want to edit this code, so it could accept more client join on my server. This server is just used to accept one client's connection, and it can send, and receive messages. But I want to make it a "Multiplayer" Server. Many clients connected to one server. Here's the Server side code, and the Client side code:
I would really appreciate your help!
My Server Code:
import java.net.*;
import java.lang.*;
public class RecordAppServer {
public static void main(String[] args) throws IOException {
final int port = 8136;
System.out.println("Server waiting for connection on port "+port);
ServerSocket ss = new ServerSocket(port);
Socket clientSocket = ss.accept();
System.out.println("Recieved connection from "+clientSocket.getInetAddress()+" on port "+clientSocket.getPort());
//create two threads to send and recieve from client
RecieveFromClientThread recieve = new RecieveFromClientThread(clientSocket);
Thread thread = new Thread(recieve);
thread.start();
SendToClientThread send = new SendToClientThread(clientSocket);
Thread thread2 = new Thread(send);
thread2.start();
}}
class RecieveFromClientThread implements Runnable
{
Socket clientSocket=null;
BufferedReader brBufferedReader = null;
public RecieveFromClientThread(Socket clientSocket)
{
this.clientSocket = clientSocket;
}//end constructor
public void run() {
try{
brBufferedReader = new BufferedReader(new InputStreamReader(this.clientSocket.getInputStream()));
String messageString;
while(true){
while((messageString = brBufferedReader.readLine())!= null){//assign message from client to messageString
if(messageString.equals("EXIT"))
{
break;//break to close socket if EXIT
}
System.out.println("From Client: " + messageString);//print the message from client
//System.out.println("Please enter something to send back to client..");
}
this.clientSocket.close();
System.exit(0);
}
}
catch(Exception ex){System.out.println(ex.getMessage());}
}
}//end class RecieveFromClientThread
class SendToClientThread implements Runnable
{
PrintWriter pwPrintWriter;
Socket clientSock = null;
public SendToClientThread(Socket clientSock)
{
this.clientSock = clientSock;
}
public void run() {
try{
pwPrintWriter =new PrintWriter(new OutputStreamWriter(this.clientSock.getOutputStream()));//get outputstream
while(true)
{
String msgToClientString = null;
BufferedReader input = new BufferedReader(new InputStreamReader(System.in));//get userinput
msgToClientString = input.readLine();//get message to send to client
pwPrintWriter.println(msgToClientString);//send message to client with PrintWriter
pwPrintWriter.flush();//flush the PrintWriter
//System.out.println("Please enter something to send back to client..");
}//end while
}
catch(Exception ex){System.out.println(ex.getMessage());}
}//end run
}//end class SendToClientThread
My Client Code:
import java.io.*;
import java.net.*;
public class RecordAppClient {
public static void main(String[] args)
{
try {
Socket sock = new Socket("192.168.0.2",8136);
SendThread sendThread = new SendThread(sock);
Thread thread = new Thread(sendThread);thread.start();
RecieveThread recieveThread = new RecieveThread(sock);
Thread thread2 =new Thread(recieveThread);thread2.start();
} catch (Exception e) {System.out.println(e.getMessage());}
}
}
class RecieveThread implements Runnable
{
Socket sock=null;
BufferedReader recieve=null;
public RecieveThread(Socket sock) {
this.sock = sock;
}//end constructor
public void run() {
try{
recieve = new BufferedReader(new InputStreamReader(this.sock.getInputStream()));//get inputstream
String msgRecieved = null;
while((msgRecieved = recieve.readLine())!= null)
{
System.out.println("From Server: " + msgRecieved);
//System.out.println("Please enter something to send to server..");
}
}catch(Exception e){System.out.println(e.getMessage());}
}//end run
}//end class recievethread
class SendThread implements Runnable
{
Socket sock=null;
PrintWriter print=null;
BufferedReader brinput=null;
public SendThread(Socket sock)
{
this.sock = sock;
}//end constructor
public void run(){
try{
if(sock.isConnected())
{
System.out.println("Client connected to "+sock.getInetAddress() + " on port "+sock.getPort());
this.print = new PrintWriter(sock.getOutputStream(), true);
while(true){
//System.out.println("Type your message to send to server..type 'EXIT' to exit");
brinput = new BufferedReader(new InputStreamReader(System.in));
String msgtoServerString=null;
msgtoServerString = brinput.readLine();
this.print.println(msgtoServerString);
this.print.flush();
if(msgtoServerString.equals("EXIT"))
break;
}//end while
sock.close();}}catch(Exception e){System.out.println(e.getMessage());}
}//end run method
}//end class
You'll need to implement a multithreaded server.
The general structure will be the following:
while(true) {
1) Wait for client requests (Socket client = server.accept();)
2) Create a thread with the client socket as parameter
a) The new thread creates I/O streams (just like youre doing
with the PrintWriter and BufferedReader objects)
b) Communicate with client (in your example -
brBufferedReader.readLine())
3) Remove thread once the service is provided.
}
I suggest you take a look at the Oracle documentation:
https://www.oracle.com/technetwork/java/socket-140484.html#multi
This might also be useful:
http://tutorials.jenkov.com/java-multithreaded-servers/multithreaded-server.html
Investigating the Servlets I've created a simple chat and tested it on local IP - everything works. But when I tried to test it through the real network the connection refused - java.net.ConnectException: Connection refused: connect. Is the reason in Dynamic IP which I have, or additional settings are needed? Thanks in advance!
Server:
/**
* Created by rnd on 7/4/2017.
*/
import java.io.*;
import java.net.*;
import java.nio.charset.Charset;
import java.nio.charset.StandardCharsets;
import java.util.*;
public class VerySimpleChatServer {
ArrayList clientOutputStreams;
public static void main (String[] args) {
new VerySimpleChatServer().go();
}
public void go() {
clientOutputStreams = new ArrayList();
try {
ServerSocket serverSock = new ServerSocket(5000);
while(true) {
Socket clientSocket = serverSock.accept();
Charset charset = StandardCharsets.UTF_8;
OutputStreamWriter osw = new OutputStreamWriter( clientSocket.getOutputStream(), charset );
PrintWriter writer = new PrintWriter( new BufferedWriter( osw ) );
// PrintWriter writer = new PrintWriter(clientSocket.getOutputStream());
writer.println("Welcome to the chat 7 kids.... Семеро Козлят");
writer.flush();
clientOutputStreams.add(writer);
Thread t = new Thread(new ClientHandler(clientSocket));
t.start() ;
System.out.println("got a connection");
}
} catch(Exception ex) {
ex.printStackTrace();
}
} // Закрываем go
public class ClientHandler implements Runnable {
BufferedReader reader;
Socket sock;
public ClientHandler(Socket clientSocket) {
try {
sock = clientSocket;
InputStreamReader isReader = new InputStreamReader(sock.getInputStream(), StandardCharsets.UTF_8);
reader = new BufferedReader(isReader);
} catch(Exception ex) {ex.printStackTrace();}
} // Закрываем конструктор
public void run() {
String message;
try {
while ((message = reader.readLine()) != null) {
System.out.println("read " + message);
tellEveryone(message);
} // Закрываем while
} catch(Exception ex) {ex.printStackTrace();}
} // Закрываем run
} // Закрываем вложенный класс
public void tellEveryone(String message) {
Iterator it = clientOutputStreams.iterator();
while(it.hasNext()) {
try {
PrintWriter writer = (PrintWriter) it.next();
writer.println(message);
writer.flush();
} catch(Exception ex) {
ex.printStackTrace();
}
} // Конец цикла while
} // Закрываем tellEveryone
} // Закрываем класс
Client:
/**
* Created by rnd on 7/4/2017.
*/
import java.io.*;
import java.net.*;
import java.nio.charset.Charset;
import java.nio.charset.StandardCharsets;
import java.util.*;
import javax.swing.*;
import java.awt.*;
import java.awt.event.*;
public class SimpleChatClient {
JTextArea incoming;
JTextField outgoing;
BufferedReader reader;
PrintWriter writer;
Socket sock;
public static void main(String[] args) {
SimpleChatClient client = new SimpleChatClient();
client.go();}
public void go(){
JFrame frame = new JFrame("Ludicrously Simple Chat Client");
JPanel mainPanel = new JPanel();
incoming = new JTextArea(15,50);
incoming.setLineWrap(true);
incoming. setWrapStyleWord (true) ;
incoming.setEditable(false);
JScrollPane qScroller = new JScrollPane(incoming);
qScroller. setVerticalScrollBarPolicy (ScrollPaneConstants.VERTICAL_SCROLLBAR_ALWAYS) ;
qScroller. setHorizontalScrollBarPolicy (ScrollPaneConstants.HORIZONTAL_SCROLLBAR_ALWAYS) ;
outgoing = new JTextField(20);
JButton sendButton = new JButton("Send") ;
sendButton.addActionListener(new SendButtonListener());
mainPanel.add(qScroller);
mainPanel.add(outgoing);
mainPanel.add(sendButton);
setUpNetworking();
Thread readerThread = new Thread(new IncomingReader());
readerThread.start();
frame.getContentPane().add(BorderLayout.CENTER, mainPanel);
frame.setSize(800,500);
frame.setVisible(true);
}
private void setUpNetworking() {
try {
sock = new Socket("178.165.87.221", 5000);
InputStreamReader streamReader = new InputStreamReader(sock.getInputStream(), StandardCharsets.UTF_8 );
reader = new BufferedReader(streamReader);
Charset charset = StandardCharsets.UTF_8;
OutputStreamWriter osw = new OutputStreamWriter( sock.getOutputStream(), charset );
writer = new PrintWriter( new BufferedWriter( osw ) );
// writer = new PrintWriter(sock.getOutputStream());
System.out.println("networking established");
} catch (IOException ex) {
ex.printStackTrace();}
}
public class SendButtonListener implements ActionListener {
public void actionPerformed (ActionEvent ev) {
try {
writer.println(outgoing.getText());
writer.flush();
} catch(Exception ex) {
ex.printStackTrace();
}
outgoing. setText ("") ;
outgoing.requestFocus () ;}
}
public class IncomingReader implements Runnable{
#Override
public void run() {
String message;
try{
while((message=reader.readLine())!=null ){
System.out.println("read " + message);
incoming.append(message + "\n");
}
} catch (Exception ex) {
ex.printStackTrace();
}
}
}
}
If you really have a dynamic ip, you can get yourself a freedns domain (and add a firewall exception), but most probably you're behind NAT. To make it work you need multiple things:
Still, get a freedns domain and setup automatic ip address update
hardcode the domain in the client
expose a fixed set of UDP ports by sending UDP packets to nowhere. The UDP port number on public ip usually matches the port number on your host. This part is the most important. You can check it works using public STUN/TURN servers.
Hardcode this set of ports into the client. It should try all ports on the freedns domain, until it finds a working port
The handshake packets should have a signature unique for your chat so both sides know they're trying to connect to the right software
As it appears, most NATs are Port-restricted cone NATs, that is, they drop incoming UDP packets from a peer until you send a packet to that peer. Besides, NAT UDP mappings you create by sending a packet expire in around 60 seconds, which is much less than for TCP mappings.
All this makes pure p2p messaging impossible for parties behind NAT. To join a p2p network you still need to exchange a few packets via a public server (e-mail or another Instant messaging provider). There's the library "ice4j" that can produce and parse these packets (SDP) and then create java socket wrappers for direct connections.
And even if two peers save each other's addresses to connect directly in the future, the addresses will eventually expire due to dynamic ip (usually 24h).
Sounds like either a firewall refusing the connection or a router is not port forwarding, so the request is just being refused. It doesn't sound like anything to do with having a dynamic IP.
If you are behind a router then there are settings in the router to allow port forwarding, and you might need to add a rule to your firewall. Anyway you can test by just trying to ping the server IP address from elsewhere and if that responds then even try a telnet <server ip> port to see if you can connect.
Something is getting in the way and refusing the connection!
I'm trying to make a simple client-server networking program. Initially, I was not running the Server and Client objects concurrently. The command prompt would just get stuck on trying to run the program. I then decided to use threads. The result is the same; I believe I have to use wait() and notify() somewhere but I'm not able to get it.
The Server needs to run first, but it will have to wait for the incoming Socket reference before it can proceed. I believe some lines need to be shifted here and there before a wait-and-notify mechanism is implemented. Here's my code so far -:
package networking;
import java.net.*;
import java.io.*;
import java.util.Scanner;
class Server implements Runnable
{
ServerSocket ss;
Socket incoming;
public void run()
{
try
{
ss = new ServerSocket(8189);
incoming = ss.accept();
OutputStream outs = incoming.getOutputStream();
InputStream ins = incoming.getInputStream();
Scanner in = new Scanner(ins);
PrintWriter out = new PrintWriter(outs);
out.println("Hello, Bye to exit");
out.println("This is the server program");
out.println("It will echo client stuff");
boolean done = false;
while(!done && in.hasNextLine())
{
out.println("Echo: " + in.nextLine());
if(in.nextLine().trim().equals("Bye"))
done = true;
}
incoming.close();
}
catch(IOException e)
{
System.err.println(e.getMessage());
}
}
}
class Client implements Runnable
{
Socket s;
public void run()
{
try
{
s = new Socket("localhost", 8189);
InputStream ins = s.getInputStream();
OutputStream outs = s.getOutputStream();
Scanner in = new Scanner(ins);
PrintWriter out = new PrintWriter(outs);
while(in.hasNextLine())
System.out.println("Client: " + in.nextLine());
out.println("Bye");
s.close();
}
catch(IOException e)
{
System.err.println(e.getMessage());
}
}
}
public class Networking
{
public static void main(String... args)
{
Thread server = new Thread(new Server());
Thread client = new Thread(new Client());
server.start();
client.start();
}
}
Any tips and pointers would be much appreciated; I just need a nod(or more) in the right direction.
Your code for opening serve and client is correct. But the problem is in the while loop for reading or writing data it falls in a deadlock. Because after establishing the connection booth server and client is waiting for each other to write something in the stream. Try with this.
class Server implements Runnable {
ServerSocket ss;
Socket incoming;
public void run() {
try {
System.out.println("Server STarted");
ss = new ServerSocket(8189);
incoming = ss.accept();
System.out.println("Client accepted");
OutputStream outs = incoming.getOutputStream();
InputStream ins = incoming.getInputStream();
Scanner in = new Scanner(ins);
PrintWriter out = new PrintWriter(outs);
out.println("Hello, Bye to exit");
out.println("This is the server program");
out.println("It will echo client stuff");
boolean done = false;
while (!done) { // && in.hasNextLine()
// out.println("Echo: " + in.nextLine());
// if (in.nextLine().trim().equals("Bye")) {
// done = true;
// }
out.println("TEsting from server");
}
incoming.close();
System.out.println("End server");
} catch (IOException e) {
System.err.println(e.getMessage());
}
}
}
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.