Having multiple clients connecting to Java Server - java

I'm creating a simple socket server using Java. I am able to connect one client at a time, I tried to implement Threads to handle multiple client. In my Server constructor I created a thread that handles the ServerSocket, and should keep listening for new clients. Once a socket is connected then I tried to create another thread to handle the client Socket. But I am still not able to connect more than one client. The second client I try to connect will not get IO streams.
public class Server extends JFrame {
private JTextField enterField;
private JTextArea displayArea;
private ObjectOutputStream output;
private ObjectInputStream input;
private ServerSocket server;
private Socket connection;
private int counter = 1;
public Server() {
super("Server");
enterField = new JTextField();
enterField.setEditable(false);
enterField.addActionListener(new ActionListener() {
#Override
public void actionPerformed(ActionEvent event) {
sendData(event.getActionCommand());
enterField.setText("");
}
});
add(enterField, BorderLayout.NORTH);
displayArea = new JTextArea();
add(new JScrollPane(displayArea));
setSize(300, 150);
setLocation(500, 500);
setVisible(true);
new Thread(new Runnable() {
public void run() {
try {
server = new ServerSocket(50499, 100);
displayMessage("Listening on Port: "
+ server.getLocalPort() + "\n");
for (;;) {
Socket nextClient = server.accept();
displayMessage("Client Connected");
new ClientThread(nextClient).start();
nextClient = null;
}
} catch (IOException exception) {
exception.printStackTrace();
}
}
}).start();
}
private void closeConnection() {
displayMessage("\nTerminating connection\n");
setTextFieldEditable(false);
try {
output.close();
input.close();
connection.close();
} catch (IOException ioException) {
ioException.printStackTrace();
}
}
private void displayMessage(final String string) {
SwingUtilities.invokeLater(new Runnable() {
#Override
public void run() {
displayArea.append(string);
}
});
}
private void setTextFieldEditable(final boolean editable) {
SwingUtilities.invokeLater(new Runnable() {
#Override
public void run() {
enterField.setEditable(editable);
}
});
}
private void sendData(String message) {
try {
output.writeObject("SERVER>>> " + message);
output.flush();
displayMessage("\nSERVER>>> " + message);
} catch (IOException ioException) {
displayArea.append("\nError Writing Object");
}
}
private class ClientThread extends Thread {
public ClientThread(Socket socket) throws IOException {
try {
connection = socket;
output = new ObjectOutputStream(socket.getOutputStream());
output.flush();
input = new ObjectInputStream(socket.getInputStream());
displayMessage("Got I/O Stream\n");
displayMessage("Connection " + counter + " received from: "
+
connection.getInetAddress().getHostName());
counter++;
String message = "Connection Sucessful";
sendData(message);
setTextFieldEditable(true);
do {
message = (String) input.readObject();
displayMessage("\n" + message);
} while (!message.endsWith(">>> TERMINATE"));
} catch (ClassNotFoundException classNotFoundException) {
displayMessage("\nUnknown object type recieved");
} finally {
closeConnection();
}
}
}
}

You're doing the connection stuff inside the ClientThread constructor. Therefore the new ClientThread(...) never returns until you send a TERMINATEcommand. Put the logic inside the run() method.
private class ClientThread extends Thread {
private Socket socket;
// The queue, thread-safe for good measure
private Queue<String> queue = new ConcurrentLinkedQueue<String>();
public ClientThread(Socket socket) throws IOException {
this.socket = socket;
}
public void send(String message) {
if (message != null) {
this.sendQueue.add(message);
}
}
public void run() {
try {
connection = socket;
output = new ObjectOutputStream(socket.getOutputStream());
output.flush();
input = new ObjectInputStream(socket.getInputStream());
displayMessage("Got I/O Stream\n");
displayMessage("Connection " + counter + " received from: "
+ connection.getInetAddress().getHostName());
counter++;
String message = "Connection Sucessful";
sendData(message);
setTextFieldEditable(true);
do {
// Purge the queue and send all messages.
while ((String msg = queue.poll()) != null) {
sendData(msg);
}
message = (String) input.readObject();
displayMessage("\n" + message);
} while (!message.endsWith(">>> TERMINATE"));
} catch (ClassNotFoundException classNotFoundException) {
displayMessage("\nUnknown object type recieved");
} finally {
closeConnection();
}
}
}
Tipically, you'll send messages to the connection from other threads:
ClientThread client = new ClientThread(newClient);
client.start();
client.send("Hi there");
Personally, I would have used a non-blocking (NIO) networking library such as Netty or Mina to implement this sort of stuff. There's some learning to do to use them but I think its worth it. Non-blocking means that you don't dedicate a separate thread for each connection but rather you're notified when something is received in the socket.

You did not provide implementation of run method for Thread Class.
Put processing logic of ClientThread inside run method
To keep your code modularised and more manageable make your ClientThread class public and share only necessary resources between those thread.
public class ClientThread extends Thread { //make class public
private Socket socket;
// define all other references
ObjectOutputStream output = null;
//...
public ClientThread(Socket socket) throws IOException {
this.socket = socket;
}
public void run() {
try {
connection = socket;
output = new ObjectOutputStream(socket.getOutputStream());
output.flush();
input = new ObjectInputStream(socket.getInputStream());
displayMessage("Got I/O Stream\n");
displayMessage("Connection " + counter + " received from: "
+
connection.getInetAddress().getHostName());
counter++;
String message = "Connection Sucessful";
sendData(message);
setTextFieldEditable(true);
do {
message = (String) input.readObject();
displayMessage("\n" + message);
} while (!message.endsWith(">>> TERMINATE"));
} catch (ClassNotFoundException classNotFoundException) {
displayMessage("\nUnknown object type recieved");
} finally {
closeConnection();
}
}
}}

Related

TCP Java Android Server / C# Windows Client Communication not working

I am currently trying to set up an App for an Android Device, which can communicate with Devices in the same Network via TCP connection. Said Devices run on Windows and therefore I created a simple C# TCP Client program to connect to the TCP Server. The connection gets established when the Server App is already running and a Client tries to connect to it. Both sides (Server/Client) confirm that the connection got established. When I send data from the server via DataOutputStream back to the client, the client confirms, that he got the message. But when I try to send data from the client and try to read it on the server via InputStreamReader the server never reacts to incoming messages.
Below lies the Java Android server code:
public class TCPServer {
public enum ServerCommands { TURN_OFF }
private static ServerSocket serverSocket;
private static final Handler HANDLER = new Handler(Looper.getMainLooper());
private static final int SERVERPORT = 5040;
private static final HashMap<InetAddress, ServerClientCommunicationThread> connectedClientThreads = new HashMap<>();
private interface OnUpdateUIListener {
void onShowStatus(String status);
}
private static OnUpdateUIListener listener;
public static void InitServer(Consumer<String> showStatus) {
listener = new OnUpdateUIListener() {
#Override
public void onShowStatus(String status) {
// Use the handler so we're not trying to update the UI from the bg thread
HANDLER.post(new Runnable(){
#Override
public void run(){
showStatus.accept(status);
}
});
}
};
Thread serverThread = new Thread(new ServerThread());
serverThread.start();
}
public static void OnStop(){
try {
serverSocket.close();
} catch (IOException e) {
e.printStackTrace();
}
}
public static void SendMessageToClient(InetAddress clientIP, ServerCommands action){
ServerClientCommunicationThread clientThread = connectedClientThreads.get(clientIP);
listener.onShowStatus("Trying to send Data to client!");
if (clientThread != null)
clientThread.getHandler().sendEmptyMessage(action.ordinal());
}
private static class ServerThread implements Runnable {
public void run() {
Socket socket = null;
try {
serverSocket = new ServerSocket(SERVERPORT);
} catch (IOException e) {
e.printStackTrace();
}
boolean error = false;
while (!Thread.currentThread().isInterrupted() && !error) {
try {
listener.onShowStatus("Start listening for clients!");
socket = serverSocket.accept();
listener.onShowStatus("Found client: " + socket.getInetAddress());
ClientServerCommunicationThread clientCommThread = new ClientServerCommunicationThread(socket);
new Thread(clientCommThread).start();
ServerClientCommunicationThread serverCommThread = new ServerClientCommunicationThread("CommThread", socket);
new Thread(serverCommThread).start();
connectedClientThreads.put(serverCommThread.clientSocket.getInetAddress(), serverCommThread);
} catch (Exception e) {
listener.onShowStatus("Could not establish client connection: " + e);
error = true;
}
}
}
}
private static class ServerClientCommunicationThread extends HandlerThread {
private DataOutputStream outputStream;
private Socket clientSocket;
private Handler commHandler;
public ServerClientCommunicationThread(String name, Socket clientSocket) {
super(name);
try {
this.clientSocket = clientSocket;
this.outputStream = new DataOutputStream(clientSocket.getOutputStream());
} catch (IOException e) {
e.printStackTrace();
listener.onShowStatus("ERROR: could not open ReaderStream: " + e);
}
}
#SuppressLint("HandlerLeak")
#Override
protected void onLooperPrepared(){
commHandler = new Handler(){
#Override
public void handleMessage(Message msg){
try {
outputStream.write(msg.what);
listener.onShowStatus("Sent action: " + msg.what);
outputStream.flush();
}
catch(Exception e){
listener.onShowStatus("Could not send data to client: " + clientSocket.getInetAddress() + " " + e);
}
}
};
listener.onShowStatus("Start Server Communication Thread");
}
public Handler getHandler(){
return commHandler;
}
}
private static class ClientServerCommunicationThread extends Thread {
private BufferedReader input;
private final Socket clientSocket;
public ClientServerCommunicationThread(Socket clientSocket){
super();
this.clientSocket = clientSocket;
try{
this.input = new BufferedReader(new InputStreamReader(clientSocket.getInputStream()));
} catch (IOException e) {
e.printStackTrace();
listener.onShowStatus("ERROR: could not open ReaderStream: " + e);
}
}
#Override
public void run(){
listener.onShowStatus("Start Client Communication Thread");
boolean connectionStable = true;
while (!Thread.currentThread().isInterrupted() && connectionStable) {
try {
String read = input.readLine();
//It never reaches this debug message!
listener.onShowStatus("Received message: " + read);
} catch (IOException e) {
e.printStackTrace();
listener.onShowStatus("ERROR: could not read message: " + e);
connectionStable = false;
}
}
try {
input.close();
clientSocket.close();
} catch (IOException ex) {
ex.printStackTrace();
}
}
}
}
Below lies my C# client code.
I am using the SuperSimpleTCP library for my C# code.
namespace SimpleTCPProgram
{
internal class TCPClient
{
private static SimpleTcpClient tcpClient;
private static int udpPort = 5041;
private static int tcpPort = 5040;
private static string macAddr;
enum ServerCommands { TURN_OFF = 0 }
// Main Method
static public void Main(String[] args)
{
InitTCPClient("192.168.1.4");
Console.ReadKey();
tcpClient.Send("Hello there");
Console.WriteLine("Sent data: " + tcpClient.Statistics.SentBytes.ToString());
Console.ReadKey();
}
private static void InitTCPClient(string serverIP)
{
try
{
tcpClient = new SimpleTcpClient(serverIP + ":" + tcpPort);
tcpClient.Events.Connected += Events_Connected;
tcpClient.Events.Disconnected += Events_Disconnected;
tcpClient.Events.DataReceived += Events_DataReceived;
tcpClient.Connect();
}
catch (Exception ex)
{
Console.WriteLine(ex.ToString());
}
}
private static void Events_Connected(object sender, ConnectionEventArgs e)
{
Console.WriteLine("Connected to Server: " + e.IpPort);
}
private static void Events_Disconnected(object sender, ConnectionEventArgs e)
{
}
private static void Events_DataReceived(object sender, SuperSimpleTcp.DataReceivedEventArgs e)
{
string dataString = Encoding.UTF8.GetString(e.Data);
Console.WriteLine("Received Data: " + dataString);
ServerCommands serverCommand = (ServerCommands)int.Parse(dataString);
switch (serverCommand)
{
case ServerCommands.TURN_OFF:
var psi = new ProcessStartInfo("shutdown", "/s /t 0");
psi.CreateNoWindow = true;
psi.UseShellExecute = false;
Process.Start(psi);
break;
default:
break;
}
}
}
}
Wireshark seems to confirm that the message has been sent to the server.
It even catches a message sent back by the server to the client in response.
I am testing this on a test-router which doesn't have internet access and no firewall active.
My server app has the following permissions:
<uses-permission android:name="android.permission.ACCESS_NETWORK_STATE" tools:ignore="ManifestOrder"/>
<uses-permission android:name="android.permission.INTERNET" />
<uses-permission android:name="android.permission.ACCESS_WIFI_STATE"/>
<uses-permission android:name="android.permission.CHANGE_WIFI_MULTICAST_STATE"/>
<uses-permission android:name="android.permission.FOREGROUND_SERVICE" />
TLDR: My Android java server doesn't get any C# client messages sent via TCP connection.

Code of new thread after accepting the connection in TCP server isn't executed

I have the following tcp server:
public class Server {
private Connection db;
private Statement statement;
private ServerSocket socket;
public static void main(String[] args) {
Server server = new Server();
server.initializeServer();
System.out.println("Server initialized");
server.listenConnections();
}
private void initializeServer() {
try {
db = DriverManager.getConnection("jdbc:mysql://localhost:3306/courseworkschema" +
"?verifyServerCertificate=false" +
"&useSSL=false" +
"&requireSSL=false" +
"&useLegacyDatetimeCode=false" +
"&amp" +
"&serverTimezone=UTC",
"Sergei",
"12345");
statement = db.createStatement();
socket = new ServerSocket(1024);
} catch (SQLException | IOException e) {
e.printStackTrace();
}
}
private void listenConnections() {
System.out.println("Listening connections ... ");
while (true) {
try {
Socket client = socket.accept();
new Thread(() -> {
System.out.println("Client accepted");
try {
OutputStream outputStream = client.getOutputStream();
InputStream inputStream = client.getInputStream();
String clientAction;
String queryContent;
boolean flag = true;
while (flag) {
byte[] msg = new byte[100];
int k = inputStream.read(msg);
clientAction = new String(msg, 0, k);
clientAction = clientAction.trim();
msg = new byte[100];
k = inputStream.read(msg);
queryContent = new String(msg, 0, k);
queryContent = queryContent.trim();
System.out.println(clientAction);
System.out.println(queryContent);
if (clientAction.equalsIgnoreCase("END")) {
flag = false;
}
else if (clientAction.equalsIgnoreCase("LOGIN")) {
System.out.println("Login action");
}
}
} catch (IOException e) {
e.printStackTrace();
}
});
} catch (IOException e) {
e.printStackTrace();
}
}
}
}
This server is created to communicate with database. Here's the way how I try to connect to this serverL
public class LoginController {
private LoginWindow window;
private Socket socket;
private InputStream is;
private OutputStream os;
public LoginController() {
connectToServer();
}
public void logInUser(String login, String password) {
if (!login.isEmpty() && !password.isEmpty()) {
sendDataToServer("LOGIN");
sendDataToServer("");
} else {
window.showMessageDialog("Fill the fields!", JOptionPane.ERROR_MESSAGE);
}
}
public void attachView(LoginWindow window) {
this.window = window;
}
private void connectToServer() {
try {
socket = new Socket("127.0.0.1", 1024);
System.out.println("Connected");
} catch (IOException e) {
e.printStackTrace();
}
}
private void sendDataToServer(String res) {
try {
os = socket.getOutputStream();
os.write(res.getBytes());
} catch (IOException e) {
e.printStackTrace();
}
}
}
When I run the server and then client, I have such logs in server:
Server initialized
Listening connections ...
Process finished with exit code -1
So, I can't understand why server doesn't wait and accept a connection from client, but closes after initializing and listening. So, what's the matter? I will appreciate any help. Thanks in advance!
UPD
When I run my app it started to work but I found out that code in Thread block isn't executed. I even can't understand, why does it happen
In your private void listenConnections() you are creating a Thread object but you are not telling it to start after its created thus it wont execute.
Your thread creation line should look something like this:
new Thread(() -> {
//your code
}).start();
From the javadocs:
https://docs.oracle.com/javase/7/docs/api/java/lang/Thread.html#start()
public void start()
Causes this thread to begin execution; the Java Virtual Machine calls
the run method of this thread. The result is that two threads are
running concurrently: the current thread (which returns from the call
to the start method) and the other thread (which executes its run
method).
It is never legal to start a thread more than once. In particular, a
thread may not be restarted once it has completed execution.
Throws: IllegalThreadStateException - if the thread was already
started.
See Also: run(), stop()

How to stop() Thread when it created on server side for client in java

when client leave the server connection how can i stop the Thread of server which is create for the communication between client and server and please tell me how can i send a single client message to all clients which are connected with that server thanks in advance :).
ChatServer.java
import java.net.*;
import java.io.*;
public class ChatServer implements Runnable
{
private ServerSocket server = null;
private Thread thread = null;
private ChatServerThread client = null;
public ChatServer(int port)
{
try
{ System.out.println("Binding to port " + port + ", please wait ...");
server = new ServerSocket(port);
System.out.println("Server started: " + server);
start();
}
catch(IOException ioe)
{ System.out.println(ioe); }
}
public void run()
{
while (thread != null)
{
try
{ System.out.println("Waiting for a client ...");
addThread(server.accept());
}
catch(IOException ie)
{ System.out.println("Acceptance Error: " + ie); }
}
}
public void addThread(Socket socket)
{ System.out.println("Client accepted: " + socket);
client = new ChatServerThread(this, socket);
try
{ client.open();
client.start();
}
catch(IOException ioe)
{ System.out.println("Error opening thread: " + ioe); }
}
public void start()
{ if (thread == null)
{ thread = new Thread(this);
thread.start();
}
}
public void stop()
{ if (thread != null)
{ thread.stop();
thread = null;
}
}
public static void main(String args[])
{ ChatServer server = null;
int x=2111;
if (x<1)
System.out.println("Usage: java ChatServer port");
else
server = new ChatServer(x);
}
}
ChatServerThread
import java.net.*;
import java.io.*;
public class ChatServerThread extends Thread
{ private Socket socket = null;
private ChatServer server = null;
private int ID = -1;
private DataInputStream streamIn = null;
public ChatServerThread(ChatServer _server, Socket _socket)
{ server = _server; socket = _socket; ID = socket.getPort();
}
public void run()
{ System.out.println("Server Thread " + ID + " running."+Thread.activeCount());
while (true)
{ try
{ System.out.println(streamIn.readUTF());
}
catch(IOException ioe) { }
}
}
public void open() throws IOException
{ streamIn = new DataInputStream(new BufferedInputStream(socket.getInputStream()));
}
public void close() throws IOException
{
if (socket != null) socket.close();
if (streamIn != null) streamIn.close();
}
}
In ChatServerThread:
public void run()
try {
// thread code
} catch(InterruptedException e) {
Thread.currentThread().interrupt();
} finally {
// cleanup code, if required
}
}
and in ChatServer:
public void stop() {
if (thread != null) {
thread.interrupt();
thread = null;
}
}
This won't stop the thread, but it signals the thread to stop what it's doing - it might or might not stop right then, or even at all, depending on what code the thread is currently executing.

Java Sockets multiple connection attempt - Can't send data to all clients

I made my one-on-one socket chat work between the server (myself) and the client (a friend in a different network). Now I'm trying to do the same but I'm trying to create multiple connections, placing them in an Executors.newFixedThreadPool(poolSize), where part of the code is taken from the ExecutorService documentation.
The server works, and accepts connections, however, the problem occurs when I try to make a second connection and send messages to it. Although each client can send messages to the server, the server can only send messages to the first client.
Here is the full code:
public class MultipleServer implements Runnable {
private final ServerSocket serverSocket;
private final ExecutorService pool;
Scanner console;
public MultipleServer(int port, int poolSize, Scanner mainconsole)
throws IOException {
serverSocket = new ServerSocket(port);
pool = Executors.newFixedThreadPool(poolSize);
console = mainconsole;
}
public void run() {
try {
for(;;) {
pool.execute(new Handler(serverSocket.accept(), console));
}
} catch (IOException ex) {
pool.shutdown();
}
}
}
class Handler implements Runnable {
private Socket socket;
private Scanner console;
private String name = "undefined";
Handler(Socket socket, Scanner console)
{
this.socket = socket;
this.console = console;
}
public void run()
{
if (socket.isConnected())
{
System.out.println("connection from " + socket.getLocalAddress().getHostAddress());
Thread inputthread = new Thread(new Runnable()
{
#Override
public void run()
{
PrintWriter out;
try
{
out = new PrintWriter(socket.getOutputStream(), true);
out.println("Welcome to my server. Input your name");
out.flush();
String line;
while ((line = console.nextLine()) != null)
{
if (line.contains("/"))
{
if (line.equals("/q " + name))
{
out.println("Connection closing");
System.out.println("Connection to " + name + "closing");
out.close();
socket.close();
} else if (line.substring(0, name.length() + 3).equals("/m " + name))
{
out.println(line.substring(name.length() + 4));
out.flush();
}
} else
{
System.out.println("Incorrect command");
}
}
if (socket.isClosed())
{
out.close();
}
} catch (IOException e)
{
e.printStackTrace();
}
}
});
Thread outputthread = new Thread(new Runnable()
{
int msgno = 0;
#Override
public void run()
{
BufferedReader in;
try
{
in = new BufferedReader(new InputStreamReader(socket.getInputStream()));
while (!socket.isClosed())
{
while (!in.ready())
{
Thread.sleep(100);
}
String msg = in.readLine();
if (msgno == 0)
{
name = msg;
msgno++;
} else
{
System.out.println(name + ": " + msg);
}
synchronized (this)
{
this.wait(100);
}
}
if (socket.isClosed())
{
in.close();
}
} catch (IOException e)
{
e.printStackTrace();
} catch (InterruptedException e)
{
e.printStackTrace();
}
}
});
inputthread.start();
outputthread.start();
}
}
public static void main(String[] args) throws IOException
{
int connections = 10;
int port = 80;
Scanner scanner = new Scanner(System.in);
MultipleServer server = new MultipleServer(port, connections, scanner);
server.run();
}
}
More specifically, the exception thrown:
Exception in thread "Thread-2" java.lang.IndexOutOfBoundsException: end
at java.util.regex.Matcher.region(Unknown Source)
at java.util.Scanner.findPatternInBuffer(Unknown Source)
at java.util.Scanner.findWithinHorizon(Unknown Source)
at java.util.Scanner.nextLine(Unknown Source)
at Handler$1.run(MultipleServer.java:61)
at java.lang.Thread.run(Unknown Source)
Where the line in question is:
while((line=console.nextLine())!=null){
To clarify: this exception happens when the second user joins the server. When I type /m user1 message the first user gets the intended message, when I type /m user2 message, there are no errors, but the user2 doesn't get the message. Moreover, there is no "Incorrect command" message at the server console, meaning that the output to the second user isnt working
The main problem - you have too complicated threads management: several threads tries to read from console input simultaneously: user 1 reader thread and user 2 read thread.
You should introduce a single router thread, responsible for communication with administrator and manage all messages between spawned threads via shared concurrent structure(s).
For such tasks it would be better to use any existent frameworks, e.g. netty or nirvana messaging.

Socket server build issue

The socket server listed in step 3 from http://pirate.shu.edu/~wachsmut/Teaching/CSAS2214/Virtual/Lectures/chat-client-server.html builds cleanly (java version "1.7.0_02") and runs without error but it exits without error instead of waiting to accept clients.
Updated ChatServer with missing arg code:
ChatServer:
import java.net.*;
import java.io.*;
public class ChatServer implements Runnable
{ private ServerSocket server = null;
private Thread thread = null;
private ChatServerThread client = null;
public ChatServer(int port)
{ try
{ System.out.println("Binding to port " + port + ", please wait ...");
server = new ServerSocket(port);
System.out.println("Server started: " + server);
start();
}
catch(IOException ioe)
{ System.out.println(ioe); }
}
public void run()
{ while (thread != null)
{ try
{ System.out.println("Waiting for a client ...");
addThread(server.accept());
}
catch(IOException ie)
{ System.out.println("Acceptance Error: " + ie); }
}
}
public void addThread(Socket socket)
{ System.out.println("Client accepted: " + socket);
client = new ChatServerThread(this, socket);
try
{ client.open();
client.start();
}
catch(IOException ioe)
{ System.out.println("Error opening thread: " + ioe); }
}
public void start() {
thread = new Thread(this);
thread.start();
}
public void stop() { /* no change */ }
public static void main(String args[]) {
ChatServer server = null;
if (args.length != 1)
System.out.println("Usage: java ChatServer port");
else
server = new ChatServer(Integer.parseInt(args[0]));
}
}
ChatServerThread:
import java.net.*;
import java.io.*;
public class ChatServerThread extends Thread
{ private Socket socket = null;
private ChatServer server = null;
private int ID = -1;
private DataInputStream streamIn = null;
public ChatServerThread(ChatServer _server, Socket _socket)
{ server = _server; socket = _socket; ID = socket.getPort();
}
public void run()
{ System.out.println("Server Thread " + ID + " running.");
while (true)
{ try
{ System.out.println(streamIn.readUTF());
}
catch(IOException ioe) {
System.out.println(ioe.getMessage());
}
}
}
public void open() throws IOException
{ streamIn = new DataInputStream(new BufferedInputStream(socket.getInputStream()));
}
public void close() throws IOException
{ if (socket != null) socket.close();
if (streamIn != null) streamIn.close();
}
}
EDIT: Updating my answer with a working solution.
Change these methods in your ChatServer class in order to be like these
public void start() {
thread = new Thread(this);
thread.start();
}
public void stop() {
// You should implement this too
}
public static void main(String args[]) {
// Instantiate a CharServer with the listening port 9191
ChatServer chatServer = new ChatServer(9191);
// CharServer.start() should not be confused with Thread.start();
// This calls our custom method up above, which includes a call to
// Thread(ChatServer).start();
chatServer.start();
}
Where 9191 is a port number I made up.
Executing CharServer#main method produces the following output and stays alive
Binding to port 9191, please wait ...
Server started: ServerSocket[addr=0.0.0.0/0.0.0.0,port=0,localport=9191]
Waiting for a client ...
Waiting for a client ...
You should also implement stop() method for the sake of functionality.
{ while (thread != null)
You never set thread so it will all be null
And you never create a thread
Try changing start() to:
public void start() {
thread = new Thread(this);
thread.start();
}

Categories

Resources