multi client chat server throwing exceptions and not allowing connections after disconnect - java

It's hard to fit it in the title but every time a client disconnects, a lot of exceptions are thrown and the server does not allow any more connections after the DC. Here is the error i get:
java.net.SocketException: Socket closed
at java.net.SocketInputStream.read(Unknown Source)
at java.net.SocketInputStream.read(Unknown Source)
at java.io.ObjectInputStream$PeekInputStream.read(Unknown Source)
at java.io.ObjectInputStream$PeekInputStream.readFully(Unknown Source)
at java.io.ObjectInputStream$BlockDataInputStream.readShort(Unknown Source)
at java.io.ObjectInputStream.readStreamHeader(Unknown Source)
at java.io.ObjectInputStream.<init>(Unknown Source)
at ClientHandler.setupStreams(ClientHandler.java:34)
at ClientHandler.run(ClientHandler.java:22)
Now i expect to get this exception because yea... The client closed the connection between the server and the client. but what i can't understand is why the client wont allow connections after the first disconnect. I am assuming that it breaks out of the while loop but why? Here is the code that takes the clients connection, accepts it and hands it off to the handler class:
public class ClientConnector
{
public static JTextField userText;
public static JTextArea chatWindow;
public static int Connections = 0;
public static Vector sendQueue = new Vector();
public static ArrayList<ObjectOutputStream> Streams = new ArrayList<ObjectOutputStream>();
public static Scanner input = new Scanner(System.in);
public ClientConnector()
{
}
public static void runServer()
{
try
{
System.out.println("[Info] Attempting to bind to port 1337.");
#SuppressWarnings("resource")
ServerSocket serversocket = new ServerSocket(1337);
System.out.println("[Info] Bound to port 1337.");
System.out.println("[Info] Waiting for client connections...");
while(true)
{
Socket socket = serversocket.accept();
new ClientHandler(socket).start();
Connections += 1;
}
}
catch (IOException e)
{
e.printStackTrace();
}
}
}
That's fairly simple. Now for the code that handles the clients connection:
public class ClientHandler extends Thread
{
Socket ConnectedClient;
static ObjectOutputStream Output;
static ObjectInputStream Input;
public static boolean isError = false;
public static int updateCounter = 0;
ClientHandler(Socket socket)
{
ConnectedClient = socket;
}
public void run()
{
while(true)
{
setupStreams();//22
WhileChatting();
}
}
public void setupStreams()
{
try
{
if(isError == false)
{
Output = new ObjectOutputStream(ConnectedClient.getOutputStream());
Input = new ObjectInputStream(ConnectedClient.getInputStream());//34
ClientConnector.Streams.add(Output);
}
}
catch (IOException e)
{
isError = true;
e.printStackTrace();
}
}
public static void WhileChatting()
{
String Message = "";
do
{
try
{
if(isError == false)
{
Message = (String)Input.readObject();
for(int i = 0; i < ClientConnector.Streams.size(); i++)
{
ClientConnector.Streams.get(i).writeObject(Message);
System.out.println(Message);
}
}
}
catch(ClassNotFoundException CNFE)
{
isError = true;
CNFE.printStackTrace();
}
catch(EOFException eof)
{
for(int i = 0; i < ClientConnector.Streams.size(); i++)
{
try
{
Output.close();
Input.close();
ClientConnector.Streams.get(i).close();
ClientConnector.Streams.remove(i);
System.out.println("Connection lost");
}
catch (IOException e)
{
e.printStackTrace();
}
}
}
catch (IOException e)
{
isError = true;
e.printStackTrace();
}
}
while(Message != "/disconnect");
}
public static void sendMessage(String message)
{
try
{
if(isError == false)
{
Output.writeObject(message);
System.out.println(message);
}
}
catch(IOException Ex)
{
isError = true;
Ex.printStackTrace();
}
}
public static void sendServerMessage(String message)
{
int Limit = 0;
try
{
for(int i = 0; i < ClientConnector.Streams.size(); i++)
{
if(Limit == 0)
{
ClientConnector.Streams.get(i).writeObject("\247c[Server] \247d" + message);
System.out.println("\247c[Server] \247d" + message);
Limit = 1;
}
}
}
catch (IOException e)
{
e.printStackTrace();
}
}
public static void closeConnections()
{
try
{
if(isError == false)
{
Output.close();
Input.close();
//ConnectedClient.close();
}
}
catch(IOException Ex)
{
isError = true;
Ex.printStackTrace();
}
}
}
I have commented in the affected lines.
The error happens after the client disconnects. I don't know if it's the exception causing the while loop to break or weather it's something else. How can i make this code continute to allow incoming connectinos after the client disconnects. I have tried debugging and using System.out.println. Thanks in advance to all who answered.

Now i expect to get this exception because yea... The client closed the connection between the server and the client.
No. This exception means that you closed the Socket and then tried to do further I/O on it. Nothing to do with the peer.
but what i can't understand is why the client wont allow connections after the first disconnect.
There are numerous problems with your code.
You must use the same ObjectInputStream and ObjectOutputStream for the life of the Socket, at both ends. At present you are creating a new pair, and adding them to the data structure, every time around the loop.
When you catch EOFException on one Socket, you are closing all the sockets. You should only close one, the one you got the exception from, and then you must break out of all loops and allow the thread to exit.
You should basically change your while loop from while (true) to while (!isError) and stop testing isError everywhere else. I would get rid of the whileChatting method and incorporate it into this while loop. And you don't need the inner do loop. You only need one loop that reads until EOS or a disconnect command.

Related

Cannot able to establish an UDP connection between a client and server [duplicate]

This question already has an answer here:
(How) can I use ServerSocket to listen for UDP instead of TCP traffic?
(1 answer)
Closed 5 years ago.
Basically, I am writing a simple TCP-UDP multiclient GUI program. I can establish a TCP connection to the server but not an UDP connection. The server is listening in on port 4000. I have a comboBox on the GUI client which has elements TCP and UDP. If the user selects UDP and clicks Connect. Then it will attempt to establish a UDP connection by calling the UDPconnection method.
Here is my code for the client GUI:
public void UDPconnection()
{
try
{
done = false;
datagramSocket = new DatagramSocket(serverPort);
}
catch (SocketException e)
{
done = true;
System.out.println("Host not available");
}
}
Here is my code for the chat server:
public class chatServer2 implements Runnable {
private int clientCount = 0;
private ChatServerThread clients[] = new ChatServerThread[50];
private ServerSocket server = null;
Thread thread = null;
//same as version3
public chatServer2(int port){
try{
server = new ServerSocket(port);//step1
System.out.println("Started the server...waiting for a client");
start(); //the chatserver's start method that goes ahead and creates a new thread
}
catch(IOException e){
System.err.println("ERROR "+e.getMessage());
}
}
public void start(){
if(thread == null){
thread = new Thread(this);
thread.start();
}
}
#Override
public void run() {//same as version 3
while(thread !=null){
try{
System.out.println("Waiting for a client...");
//now we add a new Thread and accept a client
addThread(server.accept());
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
public void addThread(Socket socket){
if(clientCount < clients.length){
clients[clientCount] = new ChatServerThread(this, socket);
try {
clients[clientCount].open();//open the stream for the ChatServerThread client
clients[clientCount].start();//start to run the ChatServerThread client
clientCount++;
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
public synchronized void handle(int ID, String input)
{
System.out.println(input);
if(input.equalsIgnoreCase("bye"))
{
remove(ID);//person said bye so remove them
}
else
{
System.out.println(input);
for (int i = 0; i < clientCount; i++)
{
clients[i].send("User: " + ID + ": " + input);
}
}
}
public synchronized void remove(int ID){
int position = findClient(ID);
if(position >=0){
ChatServerThread toRemove = clients[position];
if(position <clientCount-1){
for(int i= position+1; i <clientCount; i++){
clients[i-1] = clients[i];
}
clientCount--;
}
try {
toRemove.close();//close the person's that said bye connection
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
private int findClient(int ID){
for(int i=0; i<clientCount; i++){
if(clients[i].getID() == ID){
return i;
}
}
return -1;//not in the array
}
public static void main(String [] args){
chatServer2 l = new chatServer2(4000);
}
}
There is no such thing as a 'UDP connection', for a start.
Failure to create a DatagramSocket on a specified port does not mean 'host not available'. Have a look at the exception message to see what it does mean.
UDP does not interoperate with TCP, and specifically not with Java ServerSockets. You need a DatagramSocket or DatagramChannel at both ends, and there is no connect phase: you just send datagrams back and forth.

Java multithreaded server - High CPU Utilization and java.net.SocketException: socket closed [duplicate]

This question already has an answer here:
java.net.SocketException: socket closed TCP Client Server Communication [duplicate]
(1 answer)
Closed 5 years ago.
This is the first java socket/multithreaded application that I write, therefore I would like to apologize for the atrocious code that you are about to witness.
Anyway, most of you will probably regard this code as being basic, a standard server that allows connection from more clients at a time. Also, the server has an interface with just a StopServer button, which closes the server, meanwhile the Client doesn't do anything else than just connect to the server and then disconnect afterwards.
Now, if I simply run the server class, it's ok, nothing 'bad' happens and when I close it, it closes fine, however:
1: If I run the server class, and then I run the client class once, let the client disconnect, and then try to close the server, I get the error:
java.net.SocketException: socket closed
2: Each client will add about ~30-35% of CPU utilization in just a brief run, and that utilization will remain at the "Java(TM) Platform SE Binary" process, for as long as the server continues to run. If I let a client be connected to the server for, let's say 30 seconds, the CPU utilization will reach 100%.
Also, I did a little research and I know that the "socket closed exception" means that you closed the socket, and then continued to try to use it, and also there's probably something wrong with how the server handles the disconnected clients.
Here's the code:
Server
import java.sql.*;
import java.net.*;
import java.io.*;
import java.util.*;
import java.awt.*;
import java.awt.event.*;
import javax.swing.*;
public class Server extends JFrame
{ private Connection con;
private static int port = 44444;
private boolean serverKeepGoing;
private static int uniqueId;
private ArrayList<ClientThread> al;
private ServerSocket serverSocket;
public Scanner keyboard = new Scanner(System.in);
public static void main(String[] args) throws IOException
{ Server server = new Server(port);
server.start();
}
public void ServerClose()
{
serverKeepGoing = false;
try
{
for(int i = 0; i < al.size(); ++i)
{ ClientThread tc = al.get(i);
try
{
tc.in.close();
tc.out.close();
tc.socket.close(); }
catch(IOException e) { e.printStackTrace(); }
serverSocket.close();}
}catch(Exception e) { e.printStackTrace(); }
}
public Server (int port)
{
serverInterface();
al = new ArrayList<ClientThread>();
}
public void start()
{ serverKeepGoing = true;
try
{ serverSocket = new ServerSocket(port);
System.out.println("Server is running!");
while(serverKeepGoing)
{ Socket socket = serverSocket.accept(); // accept connection. LINE 65
// ^ALSO :java.net.SocketException: socket closed
// if I was asked to stop
if(!serverKeepGoing)
{ ServerClose(); break;}
ClientThread t = new ClientThread(socket); // make a thread of it
al.add(t); // save it in the ArrayList
t.start();
}
ServerClose(); // means the server has got to be closed
}catch (IOException e) { e.printStackTrace(); System.out.println("Error in method start"); }
}
public synchronized void remove(int id) {
// scan the array list until we found the Id
for(int i = 0; i < al.size(); ++i) {
ClientThread ct = al.get(i);
// found it
if(ct.id == id) {
al.remove(i);
return;
}
}
}
class ClientThread extends Thread
{ // the socket where to listen/talk
Socket socket;
BufferedReader in;
PrintWriter out;
boolean clientKeepGoing;
// my unique id (easier for deconnection)
int id;
public ClientThread(Socket socket)
{ id = ++uniqueId;
this.socket = socket;
try
{
in = new BufferedReader(new InputStreamReader(socket.getInputStream()));
out = new PrintWriter(socket.getOutputStream(), true);
}
catch (IOException e) { return; }
}
public void run()
{
boolean clientKeepGoing = true;
while(clientKeepGoing)
{ try
{
}catch(Exception e){ e.printStackTrace(); }
}
// remove myself from the arrayList containing the list of the
// connected Clients
remove(id);
close();
}
// try to close everything
private void close()
{ clientKeepGoing = false;
try {
if(out != null) out.close();
}
catch(Exception e) {}
try {
if(in != null) in.close();
}
catch(Exception e) {};
try {
if(socket != null) socket.close();
}
catch (Exception e) {}
}
}
public void serverInterface(){
JFrame frame = new JFrame("Server");
frame.setLayout(null);
int windowWidth = 300;
int windowHeight = 400;
frame.setBounds(250, 150, windowWidth, windowHeight);
JButton stopServer = new JButton("Stop server");
stopServer.setFocusable(false);
stopServer.setBounds(60, 275, 175, 20);
frame.add(stopServer);
stopServer.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e)
{
ServerClose();
System.exit(1);
}
});
frame.setResizable(false);
frame.setDefaultCloseOperation(EXIT_ON_CLOSE);
frame.setVisible(true);
}
public void windowClosing(WindowEvent e)
{ ServerClose();
System.exit(1);
}
public void windowClosed(WindowEvent e) {}
public void windowOpened(WindowEvent e) {}
public void windowIconified(WindowEvent e) {}
public void windowDeiconified(WindowEvent e) {}
public void windowActivated(WindowEvent e) {}
public void windowDeactivated(WindowEvent e) {}
}
The 'java.net.SocketException: socket closed' is on line 65 of the code above.
Client
import java.net.*;
import java.awt.*;
import java.awt.event.*;
import java.io.*;
import java.util.*;
import javax.swing.*;
public class Client
{ private BufferedReader in;
private PrintWriter out;
private Socket socket;
private int port;
private String server;
public static void main(String[] args)
{ int portNumber = 44444;
String serverAddress = "localhost";
Client client = new Client(serverAddress, portNumber);
if(!client.start())
return;
}
public Client(String server, int port)
{ this.server = server;
this.port = port;
}
public boolean start()
{ // try to connect to the server
try {
socket = new Socket(server, port);
}
// if it failed not much I can do
catch(Exception ec) {
System.out.println("Error connectiong to server:" + ec);
ec.printStackTrace();
return false;
}
try
{
in = new BufferedReader(new InputStreamReader(socket.getInputStream()));
out = new PrintWriter(socket.getOutputStream(), true);;
}
catch (IOException eIO) {
System.out.println("Exception creating new Input/output Streams: " + eIO);
eIO.printStackTrace();
return false;
}
// creates the Thread to listen from the server
new ListenFromServer().start();
// success we inform the caller that it worked
return true;
}
class ListenFromServer extends Thread
{
public void run()
{ while(true)
{
disconnect() ;
break;
}
}
}
public void disconnect()
{ try {
if(in != null) in.close();
}
catch(Exception e) {} // not much else I can do
try {
if(out != null) out.close();
}
catch(Exception e) {} // not much else I can do
try{
if(socket != null) socket.close();
}
catch(Exception e) {} // not much else I can do
}
}
Note that this is just a fragment of the whole application that I am currently building, I tried to post only what had to do with the Server-Client communication, so I deleted everything else, I'm saying this in case you see something that maybe doesn't have any purpose, I probably omitted to delete it
I see that the question got marked as duplicate, which I consider to be unfair. Firstly, in the 'similar' question, the problem was obvious, the outpot stream was closed, which closed the socket, but the socket had still been used, meanwhile, my program closes everything alltoghether and also has the CPU problem I mentioned, for which I cannnot get any answer from the so called 'similar' question.
The high CPU utilization is because your client threads aren't doing anything else besides burning the CPU with their empty loops. As for the SocketException, it works as planned, so catch it and handle it.

Java: how to stop a server (close a Socket) without an exception?

I've made a server which allows to join many clients.
However I have a problem.
I added START/STOP button which should start/stop server. But the code does not work like I want: connection isn't closed and code goes to the IOException "THIS IS PROBLEM" (in ServerLogic part).
Additionally clients still can contact with server.
SERVER LOGIC
public class ServerLogic
{
private static ServerSocket m_sSocket;
private static Set<ServerSubscriber> m_subscriberList = new HashSet<ServerSubscriber>();
private static boolean m_isServerRun = false;
private static class ServerLogicHolder
{
static final ServerLogic INSTANCE = new ServerLogic();
}
private ServerLogic()
{}
public static ServerLogic getServerLogic()
{
return ServerLogicHolder.INSTANCE;
}
/**
* It starts listening of incoming connections from the clients.
*
* #param port
*/
public void startListening(int port)
{
try
{
if (!m_isServerRun)
{
m_sSocket = new ServerSocket(port);
K6s.getUiServerConsole().addLine(Config.LOG_START);
m_isServerRun = true;
}
else
{
System.out.println(Config.LOG_ERROR1);
}
}
catch (IOException e)
{
System.out.println(Config.LOG_ERROR1);
}
try
{
while (isServerRun())
{
new Thread(new ServerSubscriber(m_sSocket.accept(), K6s.getUiServerConsole())).start();
}
}
catch (IOException e1)
{
/*
java.net.SocketException: socket closed
at java.net.DualStackPlainSocketImpl.accept0(Native Method)
at java.net.DualStackPlainSocketImpl.socketAccept(Unknown Source)
at java.net.AbstractPlainSocketImpl.accept(Unknown Source)
at java.net.PlainSocketImpl.accept(Unknown Source)
at java.net.ServerSocket.implAccept(Unknown Source)
at java.net.ServerSocket.accept(Unknown Source)
at org.czarny.k6s.comm.ServerLogic.startListening(ServerLogic.java:69)
at org.czarny.k6s.gui.K6s$2$1.run(K6s.java:138)
at java.lang.Thread.run(Unknown Source)
*/
}
}
/**
* Just close server's socket.
*/
public void stopListening()
{
if (m_isServerRun)
{
try
{
m_isServerRun = false;
m_sSocket.close();
m_sSocket = null;
}
catch (IOException e)
{
m_isServerRun = true;
System.out.println(Config.LOG_ERROR4);
}
}
}
public HashSet<ServerSubscriber> getSubscriberList()
{
return (HashSet<ServerSubscriber>) m_subscriberList;
}
public boolean isServerRun()
{
return m_isServerRun;
}
}
CLIENT SUBSCRIBER (not neccessary code has been removed)
public class ServerSubscriber implements Runnable
{
private Socket m_socket;
private LogComponent m_serverConsole;
private PrintWriter m_outComm;
private String m_subscriberIP;
private String m_subscriberName;
private String m_subsctiberLogInfo;
ServerSubscriber(Socket socket, LogComponent serverConsole)
{
m_socket = socket;
m_serverConsole = serverConsole;
try
{
m_outComm = new PrintWriter(socket.getOutputStream(), true);
}
catch (IOException e)
{
e.printStackTrace();
}
sendMessage(Config.MSG_HANDSHAKE);
}
/**
* This method runs messages from this subscriber.
*/
public void run()
{
String line;
BufferedReader inComm = null;
try
{
inComm = new BufferedReader(new InputStreamReader(m_socket.getInputStream()));
}
catch (IOException e)
{
m_serverConsole.addLine(Config.LOG_ERROR3);
}
while (ServerLogic.getServerLogic().isServerRun())
{
try
{
//do something here
}
}
}
Button which handles START/STOP
uiStart.addActionListener(new ActionListener()
{
public void actionPerformed(ActionEvent arg0)
{
if (!ServerLogic.getServerLogic().isServerRun())
{
uiStart.setText(Config.GUI_BTN_STOP);
new Thread(new Runnable()
{
public void run()
{
try
{
ServerLogic.getServerLogic().startListening(Integer.parseInt(uiServerPort.getText()));
}
catch (Exception e)
{
e.printStackTrace();
}
}
}).start();
}
else
{
ServerLogic.getServerLogic().stopListening();
m_uiServerConsole.addLine(Config.LOG_STOP);
uiStart.setText(Config.GUI_BTN_START);
}
}
});
What I missed?
How to properly close connection without any exceptions?
Should I just before closing the Socket send to all clients some message with demand of closeure or just closing the Socket on the server should be enough?
Regards.
I added START/STOP button which should start/stop server. But the code does not work like I want: connection isn't closed
That's because you're closing the ServerSocket, not an accepted socket.
and code goes to the IOException "THIS IS PROBLEM" (in ServerLogic part).
That's normal. Nothing wrong here.
Additionally clients still can contact with server.
Existing clients can continue to use their existing connections. If you want to close those, see next. No new connections can be created.
How to properly close connection without any exceptions?
Shut them down for input. That will cause the reads to incur an end of stream, which should already cause the threads concerned to close the socket and exit.
Should I just before closing the Socket send to all clients some message with demand of closeure or just closing the Socket on the server should be enough?
Closing the socket is sufficient. Sending an extra message doesn't add any value. The clients will get the usual end-of-stream indications from their reads, or an IOException: connection reset on their writes.

Handling multi Java TCP clients with Threads

I have been working with TCP server/client stuff for a while. I am actully good at UDP programming when it comes to connecting more than one user that is multiple clients. I tried to do the same on a TCP server that i made using Threads but whenever the Thread gets to this piece of code
String reader = (String)in.readObject();
an error is generated and the thread stops executing the code but the thread still runs the program keeping it alive.
Anyway here is the entire source code :
public class TestServer implements Runnable {
private Thread run, streams, connect, receive, send;
private ServerSocket socket;
private Socket conn;
private ObjectInputStream in;
private ObjectOutputStream out;
private boolean running, incomingMessage = false;
private int port;
public TestServer(int port) throws IOException {
this.port = port;
socket = new ServerSocket(port);
console("Server stated on : " + InetAddress.getLocalHost() + " : " + port);
run = new Thread(this, "Run");
run.start();
}
public void run() {
running = true;
connect();
receive();
}
private void connect() {
connect = new Thread("Connect") {
public void run() {
while(running) {
try {
conn = socket.accept();
} catch (IOException e) {
e.printStackTrace();
}
console("You are now connected" + conn.getInetAddress().toString() + " : " + conn.getPort());
try {
setupStreams();
} catch (IOException e) {
e.printStackTrace();
}
}
}
}; connect.start();
}
private void setupStreams() throws IOException {
streams = new Thread("Streams") {
public void run() {
try {
console("Setting up Streams");
out = new ObjectOutputStream(conn.getOutputStream());
out.flush();
in = new ObjectInputStream(conn.getInputStream());
console("Streams are now setup");
incomingMessage = true;
receive.start();
} catch(IOException e) {
e.printStackTrace();
}
}
}; streams.start();
}
private void receive() {
receive = new Thread("Receive") {
public void run() {
while(incomingMessage) {
String message = "";
try {
message = (String) in.readObject();
//This is the only flaw the program
} catch (ClassNotFoundException | IOException e) {
e.printStackTrace();
}
console("Client : " + message);
}
}
};
}
private void console(String message) {
System.out.println(message);
}
public static void main(String[] args) {
try {
new TestServer(1234);
} catch (IOException e) {
e.printStackTrace();
}
}
}
FYI am not new to this. The error is caused because the server starts receiving packets even when there are no packets to be received. But because the thread forces it to receive it, i generates the error in the thread and dont know any other way to counter this. So please help. Thanks in Advance.
You shouldn't need 2 threads per connection. One thread is all that's required. After the connection is accepted, pass it to a worker thread to start reading. This can be done in a while loop in the worker thread.
Even though the socket's input stream can be read, the ObjectInputStream() class is more sensitive. If there is any error, its state is corrupted and it can't be used.
while (true) {
try {
Object input = in.readObject();
message = (String) input;
} catch (IOException e) {
e.printStackTrace();
break; //unrecoverable
} catch (ClassNotFoundException e) {
e.printStackTrace();
break; //unrecoverable
}
console("Client : " + message);
}
It's a better design to use a specific message protocol instead of sending serialized Java objects. For example if you are sending Strings like your sample, an InputStreamReader can be used to convert bytes to characters more easily and with less error handling.
These resources would be helpful to you:
https://docs.oracle.com/javase/tutorial/networking/sockets/clientServer.html#later
Java - Listening to a socket with ObjectInputStream
ObjectInputStream(socket.getInputStream()); does not work

how can I have a linked list that multiple clients can read write to?

I have a multithreaded server and can have multiple clients at once connected. These threads call a class that has multiple linked lists and the clients can add and remove information to it.
For example
This is the server
public class ShareServer {
public static void main(String[] args) throws IOException {
//if (args.length != 1) {
//System.err.println("Usage: java ShareServer <port number>");
//System.exit(1);
//}
//int portNumber = 2000;
boolean listening = true;
try (ServerSocket serverSocket = new ServerSocket(2000)) {
while (listening) {
new ClientThread(serverSocket.accept()).start();
}
} catch (IOException e) {
System.err.println("Could not listen on port " + 2000);
System.exit(-1);
}
}
}
This is the clientsthread
public class ClientThread extends Thread {
private Socket socket = null;
private ObjectOutputStream out;
private ObjectInputStream in;
FindMatch look= new FindMatch();
string fruit;
public ClientThread(Socket socket) {
super("ClientThread");
this.socket = socket;
}
public void run() {
try {
out = new ObjectOutputStream (socket.getOutputStream());
in = new ObjectInputStream (socket.getInputStream());
int count=0;
boolean flag = false;
try{
fruit = (Double)in.readObject();
flag = look.checkForMatch(string fruit);
if(flag==true)
sendMessage("found a match")
}
catch(ClassNotFoundException classnot){
System.err.println("Data received in unknown format");
}
socket.close();
}catch (IOException e) {
e.printStackTrace();
}
}
void sendMessage(string fuit)
{
try{
out.writeObject(msg);
out.flush();
System.out.println("server>" + msg);
}
catch(IOException ioException){
ioException.printStackTrace();
}
}
}
public LinkedList<String> fruitEntries = new LinkedList<Integer>();
public LinkedList<?> clientID = new LinkedList <?>();
this is the code that it calls
boolean checkFormatch(string fruit){
for(int i = 0; i< fruitEntries.length();i++){
if(fruit == fruitEntries.get(i)){
tell client at clientID(i);
fruitEntries.remove(i);
clientID.remove(i);
retutn true;
}
}
}
This code is far from perfect I just threw this together. the general idea is right though. I will have maybe 6 linked lists of info in mine.
I'm not sure how to keep track of what thread a client has either so I would appreciate help with that.
Personally I would use RMI instead of sockets. RMI handles all the messy listening threading etc.
Consider using one of the java.util.concurrent classes -- ConcurrentSkipListMap
ConcurrentHashMap
Also, when you compare Strings you need fruit.compareTo(...) which is rather slow so creating a hash is probably better.

Categories