Trouble writing a peer to peer chat System - java

This is the Problem Statement i Was Given :
Design a protocol where a server is responsible to match up two chatt clients. The server listens on a TCP port for upcoming connections.
If no client is already connected to the server to be paired, the server accepts the connecting client, and makes it wait for another client. To do that, it sends a message to the connecting client to wait. When recieving this command the client constructs another Server Socket instance to listen on a port . The client then sends a mesagge to the server that contains the port number in which the newly created server listens on.
When another client, C2, seeks a connection with the server while C1 is waiting, the server informs C2 the existence of C1 by sending a message “PEER_LOC $h:$p” to C2, where $h is the host name (or IP address) of C1 and $p is the port number on which C1 is waiting. After C2 receives this message, it seeks a connection to C1 using the obtained information.Clients get the messages from users. The two clients then exchange messages until either party sends an end of stream” (Ctrl-D in Linux). Their conservation is then terminated.Sophisticated methods may employ multiple threads, timeouts, etc., and is not required in this problem.
My issues is connecting two clients to my Server. I run my server program and then two other clients classes that are duplicated of each other only with different names. I can connect to one of them only the other one just seems to wait forever.
Theses are my classes I run.
The server:
package chatserver2;
import java.io.*;
import java.net.*;
import java.awt.*;
import java.awt.event.*;
import java.util.logging.Level;
import java.util.logging.Logger;
import javax.swing.*;
// import all the class that you will need for functionailty
// extends jframe to develop gui's in java
public class Server {
private static ObjectOutputStream output; // stream data out
private static ObjectInputStream input; // stream data in
private static ServerSocket server;
private static Socket connection; // socket means set up connetion between 2 computers
private static int n;
//Constructor
public static void main(String[] args) throws IOException {
Server obj = new Server();
obj.RunServer();
try {
while (true) {
Handler obj2 = new Handler();
obj2.start();
System.out.println("Accepted connection from "
+ connection.getInetAddress() + " at port "
+ connection.getPort());
n++;
System.out.println("Count " + n);
}
} finally {
connection.close();
}
}
public Server() {
}
// run the server after gui created
public void RunServer() {
try {
server = new ServerSocket(6789); // 1st number is port number where the application is located on the server, 2nd number is the amount of people aloud to connect
while (true) {
try {
waitForConnection(); // wait for a connection between 2 computers
setupStreams(); // set up a stream connection between 2 computers to communicate
whileChatting(); // send message to each other
// connect with someone and have a conversation
} catch (EOFException eofException) {
}
}
} catch (IOException ioException) {
ioException.printStackTrace();
}
}
//Wait for a connection then display connection information
private void waitForConnection() {
try {
connection = server.accept();
} catch (IOException ioexception) {
ioexception.printStackTrace();
}
}
// stream function to send and recive data
private void setupStreams() throws IOException {
output = new ObjectOutputStream(connection.getOutputStream()); // set up pathway to send data out
output.flush(); // move data away from your machine
input = new ObjectInputStream(connection.getInputStream()); // set up pathway to allow data in
}
// this code while run during chat conversions
private void whileChatting() throws IOException {
String message = "WAIT ";
sendMessage(message);
do {
try {
message = (String) input.readObject(); // stores input object message in a string variable
System.out.println("Message from Client " + message);
} catch (ClassNotFoundException classnotfoundException) {
}
} while (!message.equals("CLIENT - END"));// if user types end program stops
}
private void closeChat() {
try {
output.close();
input.close();
connection.close();
} catch (IOException ioexception) {
ioexception.printStackTrace();
}
}
// send message to the client
private void sendMessage(String message) {
try {
output.writeObject(message);
output.flush();
System.out.println("Message to client " + message);
} catch (IOException ioexception) {
}
}
public static class Handler extends Thread {
private Socket connection;
public Handler() {
String message = "WAIT";
}
public void run() {
System.out.println("Connect" + Server.connection);
while (true) {
try {
waitForConnection();
setupStreams();
whileChatting();
} catch (IOException ex) {
Logger.getLogger(Server.class.getName()).log(Level.SEVERE, null, ex);
}
}
}
private void waitForConnection() {
System.out.println("server" + server);
try {
connection = server.accept();
} catch (IOException ioexception) {
ioexception.printStackTrace();
}
System.out.println("Connection" + connection);
}
private void setupStreams() throws IOException {
output = new ObjectOutputStream(connection.getOutputStream()); // set up pathway to send data out
output.flush(); // move data away from your machine
input = new ObjectInputStream(connection.getInputStream()); // set up pathway to allow data in
}
private void whileChatting() throws IOException {
String message = " You are now connected ";
sendMessage(message);
do {
try {
message = (String) input.readObject();
} catch (ClassNotFoundException classnotfoundException) {
}
} while (!message.equals("CLIENT - END"));
}
private void closeChat() {
try {
output.close();
input.close();
connection.close();
} catch (IOException ioexception) {
ioexception.printStackTrace();
}
}
static private void sendMessage(String message) {
try {
output.writeObject(message);
output.flush();
} catch (IOException ioexception) {
}
}
}
}
The and one duplicated client classes C1, or C2:
package chatserver2;
import java.io.*;
import java.net.*;
import java.awt.*;
import java.awt.event.*;
import javax.swing.*;
// import all the class that you will need for functionailty
// extends jframe to develop gui's in java
public class Client1 extends JFrame {
private JTextField userInput; //
private JTextArea theChatWindow; //
private ObjectOutputStream output; // stream data out
private ObjectInputStream input; // stream data in
private Socket connection; // socket means set up connetion between 2 computers
//Constructor
public Client1() {
}
// run the server after gui created
public void RunClient() {
try {
connection = new Socket("localhost", 6789);// 1st number is port number where the application is located on the server, 2nd number is the amount of people aloud to connect
while (true) {
try {
// wait for a connection between 2 computers
setupStreams(); // set up a stream connection between 2 computers to communicate
whileChatting(); // send message to each other
// connect with someone and have a conversation
} catch (EOFException eofException) {
} finally {
closeChat();
}
}
} catch (IOException ioException) {
ioException.printStackTrace();
}
}
//Wait for a connection then display connection information
// stream function to send and recive data
private void setupStreams() throws IOException {
output = new ObjectOutputStream(connection.getOutputStream()); // set up pathway to send data out
output.flush(); // move data away from your machine
input = new ObjectInputStream(connection.getInputStream()); // set up pathway to allow data in
}
// this code while run during chat conversions
private void whileChatting() throws IOException {
String message = "";
do {
// have conversion while the client does not type end
try {
message = (String) input.readObject(); // stores input object message in a string variable
System.out.println("message " + message);
if (message.equals("WAIT")) {
ServerSocket server2 = new ServerSocket(5000);
System.out.println("Hello");
message = "5000";
sendMessage(message);
}
System.out.println("From server " + message);
} catch (ClassNotFoundException classnotfoundException) {
}
} while (!message.equals("CLIENT - END"));// if user types end program stops
}
private void closeChat() {
try {
output.close(); // close output stream
input.close(); // close input stream
connection.close(); // close the main socket connection
} catch (IOException ioexception) {
ioexception.printStackTrace();
}
}
// send message to the client
private void sendMessage(String message) {
try {
output.writeObject(" - " + message);
output.flush(); // send all data out
} catch (IOException ioexception) {
theChatWindow.append("\n ERROR: Message cant send");
}
}
//
//
public static void main(String[] args) {
Client1 obj = new Client1();
obj.RunClient();
}
}
I can connect to the first Client i run the second client waits for ever.
Any Suggestions or comments would be appreciated.

You're blocking server cycle. You should start new thread for each connection from client. I would separate waitForConnection() from downstream code in server's loop in RunServer method. So your while loop there should look like:
public static void RunClient() {
...
while (true) {
try {
final Server srv = waitForConnection(); // wait for a connection between 2 computers
new Thread(new Runnable() {
public void run() {
try {
srv.setupStreams(); // set up a stream connection between 2 computers to communicate
srv.whileChatting(); // send message to each other
// connect with someone and have a conversation
} catch (EOFException ex) {
// ex.printStackTrace();
}
}
}).start();
} catch (EOFException eofException) {
}
}
In this case you have to make Server instance for each client and your server declaration should contain non-static props related to client like:
public class Server {
private ObjectOutputStream output; // stream data out
private ObjectInputStream input; // stream data in
private static ServerSocket server;
private Socket connection; // socket means set up connetion between 2 computers
...
And Server creation should happen inside waitForConnection() like:
private static Server waitForConnection() {
try {
Socket connection = server.accept();
return new Server(connection);
} catch (IOException ioexception) {
ioexception.printStackTrace();
}
}
It's not the only way to do it. You may preserve Server class for being responsible for running main cycle in the same instance. But in this case I would create some additional class handling properties related to connection from particular client (connection, input, output).

This might help you think to bring it down to the essence, or it might not, I don't know really.
i
import java.io.IOException;
import java.net.ServerSocket;
import java.net.Socket;
public class Server implements Runnable{
private final ServerSocket serverSocket;
private Socket clientBuffer;
public Server(int port) throws IOException {
this.serverSocket = new ServerSocket(port);
}
#Override
public void run() {
while(true) {
try {
if(clientBuffer != null) {
//Accept new connection and echo ip and port, as the assignment tells you to, then set clientBuffer to null and start the process again. Change Client accordingly.
}
} catch(Exception ex) {
System.err.println(ex.getMessage());
System.exit(1);
}
}
}
}

Related

Socket inside bukkit plugin closes after use

I am trying to open a socket inside a bukkit plugin so i could send data to it using php or node but instead of socket remaining open after one use it just closes and also server does not load before this happens what should i do i am out of ideas.
Main:
public class Main extends JavaPlugin {
public void onEnable() {
saveDefaultConfig();
getConfig().options().copyDefaults(true);
System.out.println("[INFO] Main class loaded.");
start();
}
public void start() {
SocketServer server = new SocketServer();
try {
server.start(getConfig().getInt("port"), getConfig().getString("socket-password"));
System.out.println("[INFO] Main successfully called start.");
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
Socket server class:
When called this should read information convert it into array check the first item in array and use it as auth code then array should be converted into string and used in Command executor class. This works fine but after one use this just closes
public class SocketServer {
private ServerSocket serverSocket;
private Socket clientSocket;
private PrintWriter out;
private BufferedReader in;
public void start(int port, String socketpwd) throws IOException {
System.out.println("[INFO] Socket server listening on: " + port);
serverSocket = new ServerSocket(port);
clientSocket = serverSocket.accept();
out = new PrintWriter(clientSocket.getOutputStream(), true);
in = new BufferedReader(new InputStreamReader(clientSocket.getInputStream()));
Boolean enabled = true;
try {
// Socket authentication
String message = in.readLine();
String suffix[] = message.split(" ");
System.out.println("Socket auth code used: "+ suffix[0]);
System.out.println("Socket pwd is: " + socketpwd);
if (socketpwd.equals(suffix[0])) {
out.println("Auth sucessfull!");
// do the following command from args here
String command = suffix[1];
int suffixL = suffix.length;
// add arguments to command
for (int i = 2; i < suffixL; i++) {
command = command + " " + suffix[i];
}
// call req exec
System.out.println("[INFO] Socket server contacted Request executor with: " + command);
RequestExecutor.executor(command);
enabled = false;
}
else {
out.println("Unrecognised auth code!");
}
} catch (NullPointerException e) {
System.out.println("Exception prevented!");
}
}
public void stop() throws IOException {
in.close();
out.close();
clientSocket.close();
serverSocket.close();
}
}
Other problem as i mentioned is that bukkit server does not fully load before one request has been made to this socket.
Thank you for your help.
First of all you shouldn't be running a socket like that on the main thread, typically you should be running this on an async task using the Bukkit scheduler.
Then once you open the socket you should create a while loop to continuously poll for a connection and handle the incoming data. Instead what you are doing is opening the socket, reading a line and then dropping the connection.
You want to be doing something similar to
while(true){
Socket socket = serverSocket.accept();
}
See this webpage for some more info.

Java chat application only picking up some sent messages

I'm writing an all-in-one java chat program which will either act as a client or a server. I'm currently having this problem where, after the connection is established, the program only successfully recieves (or sends?) some of the messages. I've used a loop to spam through a load of junk and I've seen that the other end will only pick up some of the messages. I've never got a message to send manually.
Here is the code:
public class ConnectionThread implements Runnable {
private Connection c = Connection.getInstance();
private ChatInterface chatInterface;
private static ConnectionThread serverThread;
private ServerSocket serverSocket;
private Socket socket;
private ObjectInputStream dataIn;
private ObjectOutputStream dataOut;
public ConnectionThread() {}
public static synchronized ConnectionThread getInstance() {
if (serverThread == null) {
serverThread = new ConnectionThread();
}
return serverThread;
}
public void run() {
// If the programs role is server, set up the server
if (c.getRole() == ConnectionRole.SERVER) {
try {
setupServer();
waitForConnection();
setupStreams();
} catch (IOException e) {
e.printStackTrace();
}
do {
try {
chatInterface.addToChatHistory(dataIn.readUTF());
} catch (IOException e) {
e.printStackTrace();
}
} while (c.getRole() == ConnectionRole.SERVER);
}
// If the programs role is client, set up a connection to the server
if (c.getRole() == ConnectionRole.CLIENT) {
try {
setupClient();
setupStreams();
} catch (IOException e) {
e.printStackTrace();
}
do {
try {
chatInterface.addToChatHistory(dataIn.readUTF());
} catch (IOException e) {
e.printStackTrace();
}
} while (c.getRole() == ConnectionRole.CLIENT);
}
}
private void setupClient() throws IOException {
System.out.println("ATTEMPTING TO CONNECT...");
socket = new Socket("127.0.0.1", 8080);
System.out.println("CONNECTED!");
}
private void setupServer() throws IOException {
System.out.println("SETTING UP SERVER..");
serverSocket = new ServerSocket(8080, 1);
System.out.println("SERVER SETUP");
}
private void waitForConnection() throws IOException {
System.out.println("WAITING FOR A CONNECTION...");
socket = serverSocket.accept();
System.out.println("CONNECTION RECIEVED");
}
private void setupStreams() throws IOException {
System.out.println("SETTING UP STREAMS...");
dataOut = new ObjectOutputStream(socket.getOutputStream());
dataIn = new ObjectInputStream(socket.getInputStream());
chatInterface = ChatInterface.getInstance();
System.out.println("STREAMS SETUP");
}
public void sendMessage(String message) throws IOException {
System.out.println("SENDING MESSAGE...");
dataOut.writeUTF(message);
chatInterface.addToChatHistory(message);
System.out.println("MESSAGE SENT!");
}
}
Can anyone tell me why not all messages are being sent/picked up properly? I've been playing with it for quite a while now and I can't figure out why.
I found out after following EJP's recommendation to switch to DataInput/OutputStreams which worked straight away. Although I did need to be using ObjectInput/OutputStreams so I switched back. I found that I got the same issue again, until I switched to write/readObject instead of write/readUTF. If I cast the readObject to (String) it would then manage to receive every message.
So if anyone is having the same problem with ObjectInput/OutputStreams using write/readUTF try using write/readObject instead.

Getting "connection to host lost" in Java Socket Client-Server

For the server I have to alter the provided code into a multi-threaded server. For the client I have alter to it to make it read data from a text file.
So far I've managed to compile but when running on the client side it not only gives odd symbols but in the end it says "connection host lost". I've tried changing the socket number the same problem persists.
So this is what it looks like:
¼Ýsr♥Car´3▼3çw3û☻♦DmileageLmodelt↕Ljava/lang/String;Lownerq~☺L
registrationq~☺xp#
"Honda Civic""John S"q~sq~##t-sq~#Òêt
"Vokswagen"t "Maria B"q~
Connection to host lost.
This is my code for server:
//a simple client/server application: car registration
//a SERVER program that uses a stream socket connection to exchange objects
import java.net.*;
import java.io.*;
public class CarsServer {
public static void main(String[] args) throws IOException{
ServerSocket serverSocket = null;; // TCP socket used for listening
try {
/* step 1: create a server socket port number: 8000 */
serverSocket = new ServerSocket(5200);
int i = 0;
for(;;){
/* setp 2: listen for a connection and create a socket */
System.out.println("*** this server is going to register the cars ***");
System.out.println("listening for a connection...");
Socket clientSocket = serverSocket.accept();
System.out.println("Spawning " + i++);
new CarsClient(clientSocket, i).start();
}
} catch (IOException e) {
e.printStackTrace();
} finally {
/* step 5: close the connection to the client */
System.out.println("*** the server is going to stop running ***");
serverSocket.close();
}
}
}
And for Client
//a simple client/server application that exchanges OBJECTS
//a CLIENT program that uses a stream socket connection to exchange objects
import java.net.*;
import java.io.*;
class CarsClient extends Thread{
private Socket incoming;
private int client;
public CarsClient(Socket i, int c){
this.client = c;
this.incoming = i;
}
public void run(){
try {
/*
* step 2: connect input and output streams to the socket
*/
BufferedReader oisFromServer = new BufferedReader(new FileReader("Cars.txt"));
ObjectOutputStream oosToServer = new ObjectOutputStream(incoming.getOutputStream());
System.out.println("I/O streams connected to the socket");
/*
* step 3: communicate with the server
*/
Car[] cars = new Car[3];
int n = 0;
String[] l;
String line;
while((line = oisFromServer.readLine()) != null){
l = line.split(", ");
try {
// receive an object from the server
cars[n] = new Car(l[0], l[1], Integer.parseInt(l[2])); // casting!
// send an object to the server
oosToServer.writeObject(cars[n]);
//oosToServer.flush();
System.out.println("\n### send this car to the server for registration:\n" + cars[n]);
System.out.println("\t###### the car returned by the server:\n"+ cars[n]);
n++;
try {
Thread.sleep(2000);
} catch (InterruptedException e) {
}
} catch (EOFException eof) {
System.out.println("The server has terminated connection!");
} catch (IOException e) {
e.printStackTrace();
}
}
/*
* step 4: close the connection to the server
*/
System.out.println("\nClient: closing the connection...");
oosToServer.close();
oisFromServer.close();
incoming.close();
} catch (IOException ioe) {
ioe.printStackTrace();
}
System.out.println("the client is going to stop runing...");
} // end run
}
I'm new to programming so please help me out.
It appears that your issue is here:
while((line = oisFromServer.readLine()) != null){
You are consuming all the lines of text, and once that's done, oisFromServer is going to return null.
To solve this, I recommend you use the raw InputStream and InputStream.read() from the socket. Also, once upon a time I wrote a utility class for this kind of blocking reading. See DataFetcher, and its dependencies in the same project package

Why is this socket null?

I am creating a multi client chat server and i am pretty confident that it will work (Correct me if i'm wrong), I have the issue that on the socket that the client connects to is null so the connections can't be created because i use if(Socket != null) so i don't get errors but i will explain my layout real fast. The server starts with a starter class called (LaunchServer) that uses the class object ClientConnector as Minecraft and then starts the method runServer(). Here is the code for this class:
public class LaunchServer
{
public static void main(String[] args)
{
System.out.println("[Info] Running");
ClientConnector Minecraft = new ClientConnector();
Minecraft.runServer();
}
}
It's fairly simple. This brings us to the ClientConnector class. Here we start at the method runServer(). Right away we have a try catch block. in that block we print a message that the server is trying to connect to the port 1337. we then create a new ServerSocket called serversocket. We then send a message to the console saying that we have bound to port and that we are awaiting a connection. While true, we create a new Socket socket that equals ServerSocket.accept(); OMG fuck it. Heres the code. you know what it does...
import java.util.ArrayList;
import java.net.*;
import java.io.*;
public class ClientConnector
{
public static ArrayList<Socket> Connections = new ArrayList<Socket>();
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.add(socket);
}
}
catch (IOException e)
{
e.printStackTrace();
}
}
}
This takes us to the handler class:
import java.io.*;
import java.net.*;
public class ClientHandler extends Thread
{
Socket Socket;
public ClientHandler(Socket socket)
{
socket = Socket;
System.out.println("[Info] Client connected on port 1337.");
}
public void run()
{
while(true)
{
for(int i = 0; i < ClientConnector.Connections.size(); i++)
{
try
{
if(Socket != null)//This stays null...
{
ObjectOutputStream Output = new //These can't be created...
ObjectOutputStream(Socket.getOutputStream());
ObjectInputStream Input = new ObjectInputStream(Socket.getInputStream());
whileChatting(Input, Output);
}
}
catch (IOException e)
{
e.printStackTrace();
}
}
}
}
public static void sendMessage(String message, String returnedMessage, ObjectOutputStream out)
{
try
{
if(!message.isEmpty())
{
out.writeObject("\247c[Server]\247d " + message);
out.flush();
System.out.println("[Chat] Sent: " + message);
}
else
{
out.writeObject(returnedMessage);
System.out.println("[Chat] Sent: " + returnedMessage);
}
out.flush();
System.out.println("[Info] Fluching remaining data to stream.");
System.out.println("\n[Server] " + message);
}
catch(IOException ioException)
{
System.out.println("[Warning] Error: ioException # sendMessage line 76.");
}
}
public static void whileChatting(ObjectInputStream input, ObjectOutputStream output) throws IOException
{
String message = "";
do
{
try
{
message = (String) input.readObject();
System.out.println("\n" + message);
sendMessage("", message, output);
}
catch(ClassNotFoundException classNotFoundException)
{
System.out.println("[Warning] Error: ClassNotFoundException # whileChatting line 1-7.");
System.out.println("\n idk wtf that user sent!");
}
}while(!message.equals("/stop"));
}
}
Read the run method. There you will see the null problem
Would the connection get accepted then passed to the hander class? How can a null connection get accepted? My question is how can i fix this problem?
The problem is you've got a logic error due to un-recommended naming conventions. You shouldn't name variables with keywords, like your Socket variable, and each variable should have a distinguishable name. e.g. not socket1, socket2 but serverSocket, clientSocket because that will make it easier for you and anyone else to read and fix your code.
Change
Socket Socket;
to
Socket connectedSocket;
and in your constructor
socket = Socket;
to
connectedSocket = socket;
then finally, in your run() method change
if(Socket != null)
to
if(connectedSocket != null)

1 server 2 clients java

i want to make a game with 2 players .i will use udp server and 2 clients and i dont
know how to connect 2 clients to 1 server at the same time and how they will communicate.
I will use only java.At last how the mouse click will syncronize with server
public void mousePressed(MouseEvent event) {
}
public void mouseReleased(MouseEvent event) {
}
public void mouseEntered(MouseEvent event) {
}
public void mouseExited(MouseEvent event) {
}
the server
public class Provider {
public ServerSocket providerSocket;
Socket connection = null;
ObjectOutputStream out;
ObjectInputStream in;
String message;
String[] torino={"null","null"};
Provider() {}
void run()
{
try {
//1. creating a server socket (8080=port , 2 =number of connections)
providerSocket = new ServerSocket(8080, 2 );
//2. Wait for connection
System.out.println("Waiting for connection");
connection = providerSocket.accept();
System.out.println("Connection received from " + connection.getInetAddress().getHostName());
//3. get Input and Output streams
out = new ObjectOutputStream(connection.getOutputStream());
// flush= clean the object out
out.flush();
in = new ObjectInputStream(connection.getInputStream());
sendMessage("Connection successful");
//4. The two parts communicate via the input and output streams
try {
//take the message from client
message = (String)in.readObject();
if (torino[0]=="null")
torino[0]=message;
} else if (torino[1]=="null") {
torino[1]=message;
}
}
catch(ClassNotFoundException classnot) {
System.err.println("Data received in unknown format");
}
} catch(IOException ioException) {
ioException.printStackTrace();
}
finally {
//4: Closing connection
try {
in.close();
out.close();
providerSocket.close();
} catch(IOException ioException) {
ioException.printStackTrace();
}
}
}
//method to send messages from server to clients
void sendMessage(String msg)
{
try {
out.writeObject(msg);
out.flush();
System.out.println("server>" + msg);
}
catch(IOException ioException) {
ioException.printStackTrace();
}
}
//main method
public static void main(String args[])
{
Provider server = new Provider();
while(true) {
server.run();
}
}
So now you can see in your code that you have a point where the server socket is waiting for a connection. That is the accept() method. At that point, you need to create a new Thread for handling the connection and let the main thread continue waiting for another connection. You may want to keep track of the number of connections made in a variable, say numConnections.
while(numConnections < 2){
connection = providerSocket.accept();
Thread t = new Thread(new ConnectionHandler(connection));
t.start();
numConnections++;
}
Now you ConnectionHandler class will do the work of the connection:
class ConnectionHandler implements Runnable{
Socket connection;
public ConnectionHandler(Socket connection){
this.connection = connection;
}
public void run(){
//here you do all the code associated with handling the connection
//such as your Object Streams and so on.
}
}
A quick Google search turns up many tutorials and examples of doing this such as this one. There are also some YouTude videos. You may want to start with one of those.

Categories

Resources