I am building a multithread chat server.
The multi-threaded server (Manager Class) could serve many clients. It receives a message from a client, and broadcast to all clients.
The client (Peer Class) have two threads - SendThread for sending a message to the server. ReceiveThread to listen to the server broadcast.
However, while running the client program, it catches the exception and says that socket closed.
My code for the server class is below:
import java.io.*;
import java.net.ServerSocket;
import java.net.Socket;
import java.util.ArrayList;
public class Manager {
public int port;
public ArrayList<Socket> clients;
public Manager(int port) throws IOException {
this.port = port;
this.clients = new ArrayList<>();
try (ServerSocket server = new ServerSocket(port)){
System.out.println("Waiting for client connection-");
while (true){
Socket client = server.accept();
clients.add(client);
System.out.println("Client applies for connection");
Thread t = new Thread(new serverClientThread(client));
t.start();
}
}
}
public class serverClientThread implements Runnable {
private Socket client;
public serverClientThread(Socket client){
this.client = client;
}
#Override
public void run() {
try {
BufferedReader reader = new BufferedReader(new InputStreamReader(this.client.getInputStream()));
while (true){
// read
String line = reader.readLine();
if (line != null){
System.out.println("I received "+line);
// write
// broadcast
broadcast("I received " + line);
}
}
} catch (IOException e) {
e.printStackTrace();
}
}
}
// broadcast the message to all clients
public synchronized void broadcast(String message) throws IOException {
for (Socket client:this.clients){
if (client.isClosed()){
continue;
}
try (BufferedWriter writer = new BufferedWriter(new OutputStreamWriter(client.getOutputStream()))){
writer.write("I received " + message);
writer.newLine();
writer.flush();
}
}
}
}
The code of the client class is below:
import java.io.*;
import java.net.Socket;
import java.net.UnknownHostException;
import java.util.Scanner;
public class Peer {
public String hostname;
public int port;
public Peer(String hostname, int port){
this.hostname = hostname;
this.port = port;
try (Socket socket = new Socket(hostname, port)){
// create writer
BufferedWriter writer = new BufferedWriter(new OutputStreamWriter(socket.getOutputStream()));
BufferedReader reader = new BufferedReader(new InputStreamReader(socket.getInputStream()));
Thread t1 = new Thread(new SendThread(writer));
Thread t2 = new Thread(new ReceiveThread(reader));
t1.start();
t2.start();
} catch (UnknownHostException e) {
e.printStackTrace();
System.exit(-1);
} catch (IOException e) {
e.printStackTrace();
System.exit(-1);
}
}
public class SendThread implements Runnable{
private BufferedWriter writer;
public SendThread(BufferedWriter writer){
this.writer = writer;
}
#Override
public void run() {
Scanner sc = new Scanner(System.in);
while (true) {
System.out.print("Enter a String: ");
String str = sc.nextLine();
// send to server
if (str != null){
try {
this.writer.write(str);
this.writer.newLine();
this.writer.flush();
} catch (IOException e) {
e.printStackTrace();
}
}
}
}
}
public class ReceiveThread implements Runnable{
private BufferedReader reader;
public ReceiveThread(BufferedReader reader){
this.reader = reader;
}
#Override
public void run() {
while (true){
String res = null;
try {
res = this.reader.readLine();
if (res != null){
System.out.println("Server response: "+ res);
}
} catch (IOException e) {
e.printStackTrace();
System.exit(-1);
}
}
}
}
}
The error message is:
java.net.SocketException: Socket closed
at java.base/java.net.SocketInputStream.socketRead0(Native Method)
at java.base/java.net.SocketInputStream.socketRead(SocketInputStream.java:115)
at java.base/java.net.SocketInputStream.read(SocketInputStream.java:168)
at java.base/java.net.SocketInputStream.read(SocketInputStream.java:140)
at java.base/sun.nio.cs.StreamDecoder.readBytes(StreamDecoder.java:284)
at java.base/sun.nio.cs.StreamDecoder.implRead(StreamDecoder.java:326)
at java.base/sun.nio.cs.StreamDecoder.read(StreamDecoder.java:178)
at java.base/java.io.InputStreamReader.read(InputStreamReader.java:185)
at java.base/java.io.BufferedReader.fill(BufferedReader.java:161)
at java.base/java.io.BufferedReader.readLine(BufferedReader.java:326)
at java.base/java.io.BufferedReader.readLine(BufferedReader.java:392)
at Peer$ReceiveThread.run(Peer.java:86)
at java.base/java.lang.Thread.run(Thread.java:834)
It occurs in ReceiveThread in the Peer class.
Any bits of help is appreciated. Thank you!
Yige
Since you are using a try-with-resources, the socket is automatically closed immediately after you start t1 and t2.
You can think of
try (Socket socket = new Socket(hostname, port)){
// [...]
t1.start();
t2.start();
}
//
like this:
Socket socket;
try {
socket = new Socket(hostname, port)
// [...]
t1.start();
t2.start();
} catch (/* [...] */) {
} finally {
if (socket != null) {
socket.close(); // <- here the socket is closed
}
}
And since the thread is running in the background, t1.start() does not wait until thread-1 has finished -> the socket is closed.
Without try-with-resources:
public class Peer {
private Socket socket;
// [...]
public Peer(String hostname, int port) {
// [...]
try {
this.socket = new Socket(hostname, port);
// [...]
} catch (UnknownHostException | IOException ex) {
ex.printStackTrace();
System.exit(-1);
}
}
// Call this method when your program exits
public void close() {
if (this.socket != null) {
this.socket.close();
}
}
}
Related
Below is my code for a simple Concurrent Server. Whenever I run multiple clients, the server only prints out the input of the first client. I'm not sure what I've done wrong. Any help would be appreciated.
public static void main(String[] args) {
try {
ServerSocket serverSocket = new ServerSocket(8001);
while (true){
Socket clientSocket = serverSocket.accept();
System.out.println(clientSocket);
ConcurrentServer client = new ConcurrentServer(clientSocket);
client.start();
}
} catch (IOException i){}
}
public void run(){
try {
inputStream = new BufferedReader(new InputStreamReader(concurrentSocket.getInputStream()));
outputStream = new PrintWriter(new OutputStreamWriter(concurrentSocket.getOutputStream()));
String testString = inputStream.readLine();
System.out.println(testString);
} catch (IOException i){}
}
This code might help you to understand how to run multiple clients concurrently. :)
What this code does? TCP Client sends a string to the server and TCP server sends back the string in UPPERCASE format & the server can do this concurrently with multiple connections.
I have included 3 files for the server and one more for testing the server with multiple clients(ClientTest.java)
Main.java
import java.io.IOException;
public class Main {
public static void main(String[] args) {
try {
new Server(3000).start();
} catch (IOException e) {
e.printStackTrace();
}
}
}
Server.java
import java.io.IOException;
import java.net.ServerSocket;
import java.net.Socket;
import java.util.logging.Logger;
public class Server {
private ServerSocket sSocket;
private boolean run;
private int port;
public Server(int port) throws IOException {
this.port = port;
this.sSocket = new ServerSocket(this.port);
}
public void start() {
this.run = true;
Logger.getLogger(getClass().getName()).info("Server is listening on port: " + port);
try {
while (run) {
Socket cs = sSocket.accept();
Logger.getLogger(getClass().getName())
.info("New Client Connected! " + cs.getPort());
new Thread(new Client(cs)).start(); // Put to a new thread.
}
} catch (IOException e) {
Logger.getLogger(getClass().getName()).severe(e.getMessage());
}
}
public void stop() {
this.run = false;
}
}
Client.java (Client Process on server)
import java.io.*;
import java.net.Socket;
import java.util.logging.Logger;
public class Client implements Runnable {
private Socket clientSocket;
private DataOutputStream out; // write for the client
private BufferedReader in; // read from the client
public Client(Socket clientSocket) {
this.clientSocket = clientSocket;
}
#Override
public void run() {
// Do client process
outToClient(inFromClient().toUpperCase());
closeConnection();
}
private String inFromClient() {
String messageFromClient = "";
/*
* Do not use try with resources because once -
* - it exits the block it will close your client socket too.
*/
try {
in = new BufferedReader(new InputStreamReader(clientSocket.getInputStream()));
messageFromClient = in.readLine();
} catch (IOException e) {
Logger.getLogger(getClass().getName()).severe("InFromClientErr - " + e.getMessage());
}
return messageFromClient.trim().equals("") ? "No Inputs given!" : messageFromClient;
}
private void outToClient(String message) {
try {
out = new DataOutputStream(clientSocket.getOutputStream());
out.writeBytes(message);
} catch (IOException e) {
Logger.getLogger(getClass().getName()).severe("OutToClientErr - " + e.getMessage());
}
}
private void closeConnection() {
try {
in.close();
out.close();
clientSocket.close();
} catch (NullPointerException | IOException e) {
Logger.getLogger(getClass().getName()).severe(e.getMessage());
}
}
}
ClientTest.java (For Testing clients)
import java.io.*;
import java.net.Socket;
import java.util.Scanner;
public class ClientTest {
public static void main(String[] args) {
Socket clientSocket;
try {
clientSocket = new Socket("localhost", 3000);
DataOutputStream outToServer = new DataOutputStream(clientSocket.getOutputStream());
BufferedReader inFromServer = new BufferedReader(new InputStreamReader(clientSocket.getInputStream()));
outToServer.writeBytes(new Scanner(System.in).nextLine() + '\n'); // Get user input and send.
System.out.println(inFromServer.readLine()); // Print the server response.
} catch (IOException e) {
e.printStackTrace();
}
}
}
The issue was instead with the client. Not the server. The socket was declared outside of the for loop, and therefore only one connection was being created. Like so below:
public static void main(String[] args) {
try {
socket = new Socket("127.0.0.1", 8001);
for (int i = 0; i < 5; i++){
System.out.println("Starting client: " + i);
ConcurrentClient concurrentClient = new ConcurrentClient(socket, i);
concurrentClient.run();
}
} catch (IOException io) {
}
}
The Socket should be declared inside the for loop like so:
public static void main(String[] args) {
try {
for (int i = 0; i < 5; i++){
socket = new Socket("127.0.0.1", 8001);
System.out.println("Starting client: " + i);
ConcurrentClient concurrentClient = new ConcurrentClient(socket, i);
concurrentClient.run();
}
} catch (IOException io) {
}
}
I really don't know why you need so complex structure of input and output streams. It is better to use Scanner that will wait for the new input.
Also you can use PrintWriter to output the results of your conversation.
Here is server that accepts multiple clients:
import java.io.*;
import java.net.ServerSocket;
import java.net.Socket;
import java.util.Scanner;
public class ConcurrentServer extends Thread {
private Socket concurrentSocket;
public ConcurrentServer(Socket clientSocket) {
this.concurrentSocket = clientSocket;
}
public static void main(String[] args) {
try {
ServerSocket serverSocket = new ServerSocket(8001);
while (true){
Socket clientSocket = serverSocket.accept();
System.out.println(clientSocket);
ConcurrentServer client = new ConcurrentServer(clientSocket);
client.start();
}
} catch (IOException i){}
}
public void run(){
try {
InputStream inputStream = concurrentSocket.getInputStream();
Scanner scanner = new Scanner(inputStream);
OutputStream outputStream = concurrentSocket.getOutputStream();
PrintWriter pw = new PrintWriter(outputStream);
while(scanner.hasNextLine()){
String line = scanner.nextLine();
System.out.println(line);
pw.println("message: " + line);
pw.flush();
}
} catch (IOException i){}
}
}
This question already has an answer here:
no output for java client/server app [closed]
(1 answer)
Closed 5 years ago.
I've got a problem with my simple TCP/IP chat. It seems that my server doesn't receive messages from connected clients and I have no idea why it is happening.
Server code:
public class ChatServer {
public static final int MAX_CLIENTS = 10;
public static final ClientHandler[] clients = new ClientHandler[MAX_CLIENTS];
public void go(int port){
try (ServerSocket serverSocket = new ServerSocket(port)) {
System.out.println("Connection established on port "+port);
System.out.println("Waiting for clients...");
while (true){
Socket clientSocket = serverSocket.accept();
for (int i=0; i<clients.length;i++){
if (clients[i]==null){
ClientHandler clientHandler = new ClientHandler(clientSocket, clients);
clients[i] = clientHandler;
System.out.println("Added new client!");
clientHandler.start();
break;
}
}
}
} catch (IOException e) {
e.printStackTrace();
}
}
}
ClientHandler class:
public class ClientHandler extends Thread {
private Socket socket;
private ClientHandler[] clients;
private PrintWriter out;
public ClientHandler(Socket clientSocket, ClientHandler[] clientsThreads){
socket = clientSocket;
clients = clientsThreads;
}
#Override
public void run() {
ClientHandler[] threads = this.clients;
try {
BufferedReader in = new BufferedReader(new InputStreamReader(socket.getInputStream()));
out = new PrintWriter(socket.getOutputStream(), true);
for (int i=0; i<threads.length;i++){
if (threads[i]!=null){
threads[i].out.println("***SERVER: New client entered the chat room!***");
}
}
while (true){
System.out.println("in while loop - reading and writing to the client socket");
String inputLine = in.readLine();
System.out.println(inputLine);
if (inputLine.startsWith("/quit")){
break;
}
for (int i=0; i<threads.length;i++){
if (threads[i]!=null){
threads[i].out.println(inputLine);
}
}
}
System.out.println("One of the clients is leaving the chat room");
for (int i=0; i<threads.length;i++){
if (threads[i]==this){
threads[i]=null;
}
}
out.close();
in.close();
socket.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
And the client code:
public class ChatClient {
private Socket socket;
private BufferedReader in;
private PrintWriter out;
private BufferedReader stdLine;
private boolean closed = false;
public void go(String hostName, int port){
try {
initializeResource(hostName, port);
new Thread(new ServerReader()).start();
while (!closed){
out.println(stdLine.readLine().trim());
}
in.close();
out.close();
socket.close();
System.out.println("Goodbye!");
} catch (IOException e) {
e.printStackTrace();
System.out.println("Failed to connect, please try again.");
}
}
public void initializeResource(String hostName, int port) throws IOException {
socket = new Socket(hostName, port);
in = new BufferedReader(new InputStreamReader(socket.getInputStream()));
out = new PrintWriter(socket.getOutputStream());
stdLine = new BufferedReader(new InputStreamReader(System.in));
System.out.println("Connection established!");
}
public class ServerReader implements Runnable{
#Override
public void run() {
String inputLine = null;
try {
while ((inputLine=in.readLine())!=null){
System.out.println(inputLine);
if (inputLine.startsWith("Bye!")){
closed = true;
return;
}
}
in.close();
out.close();
socket.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
}
The result of running these applications for server:
Connection established on port 8000
Waiting for clients...
Added new client!
in while loop - reading and writing to the client socket
And for client:
Connection established!
***SERVER: New client entered the chat room!***
In the client version I can write messages in the terminal all the time, but none of these messages isn't received by the server (otherwise messages would be written in the server's terminal). I will appreciate any suggestion.
You need to flush after printing a line from the client:
while (!closed){
out.println(stdLine.readLine().trim());
out.flush();
}
does anyone know whats wrong with my code?
When I write something with client1 i just see it on the server and on the client1 but not on client2.
run() in Client.java:
public void run() {
Scanner input = new Scanner(System.in);
try {
Socket client = new Socket(host, port);
System.out.println("client started");
OutputStream out = client.getOutputStream();
PrintWriter writer = new PrintWriter(out);
InputStream in = client.getInputStream();
BufferedReader reader = new BufferedReader(new InputStreamReader(in));
String i = input.nextLine();
writer.write(clientname + ": " + i + newline);
writer.flush();
String s = null;
while((s = reader.readLine()) != null) {
System.out.println(s);
}
writer.close();
reader.close();
client.close();
}
If you need the Server code or anything else just ask.
Thanks in advance!!
Additionally the Server:
public class Server {
public static void main(String[] args) {
int port = 40480;
int max = 10;
ExecutorService executor = Executors.newFixedThreadPool(max);
try {
ServerSocket server = new ServerSocket(port);
System.out.print("server started" + "\n");
while(true) {
try {
Socket client = server.accept();
executor.execute(new Handler(client));
}
catch (IOException e) {
e.printStackTrace();
}
}
} catch(Exception e) {
e.printStackTrace();
}
}
}
And the Handler:
public class Handler implements Runnable{
private Socket client;
public Handler(Socket client) {
this.client = client;
}
#Override
public void run() {
try {
OutputStream out = client.getOutputStream();
PrintWriter writer = new PrintWriter(out);
InputStream in = client.getInputStream();
BufferedReader reader = new BufferedReader(new InputStreamReader(in));
String s = null;
while((s = reader.readLine()) != null) {
writer.write(s + "\n");
writer.flush();
System.out.println(s);
}
writer.close();
reader.close();
client.close();
}
catch(Exception e) {
}
}
}
This is an example - it is not complete but should give you an idea how you could multicast output to a number of listening clients. There are better ways to do this, but I wrote it similar to how you appeared to be doing the sockets. It also lacks error checking in many places and I have left that as an exercise for the reader. This code was also written so that it can be used on Java 1.6 or higher.
The code uses a list of connected Clients maintained in the Server object. When input is received from one client, the output is multicast to each client in the Client list. Writing is done via a write method in the Client class.
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.PrintWriter;
import java.net.ServerSocket;
import java.net.Socket;
import java.util.LinkedList;
import java.util.Iterator;
import java.util.List;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
public class MulticastEchoServer {
List<Client> clientList = new LinkedList<Client>();
ExecutorService executor;
int port = 40480;
int max = 10;
public MulticastEchoServer() {
this.executor = Executors.newFixedThreadPool(max);
}
public void writeToAllClients(String string) throws IOException {
// Multiple threads access this so it must be in synchronized block
synchronized (this.clientList) {
Iterator<Client> iter = this.clientList.iterator();
while (iter.hasNext())
iter.next().write(string);
}
}
public void addClient(Client client) {
// Multiple threads access this so it must be in synchronized block
synchronized (this.clientList) {
clientList.add(client);
}
}
public void removeClient(Client client) {
// Multiple threads access this so it must be in synchronized block
synchronized (this.clientList) {
clientList.remove(client);
}
}
public void listen() {
try {
ServerSocket server = new ServerSocket(port);
System.out.println("server started and listening for connections");
while (true) {
try {
Socket socket = server.accept();
System.out.print("connection accepted" + "\n");
Client newClient = new Client(this, socket);
this.addClient(newClient);
this.executor.execute(newClient);
} catch (IOException e) {
e.printStackTrace();
}
}
} catch (Exception e) {
e.printStackTrace();
}
}
public static void main(String[] args) {
new MulticastEchoServer().listen();
}
private class Client implements Runnable {
Socket socket;
PrintWriter writer;
BufferedReader reader;
MulticastEchoServer server;
public Client(MulticastEchoServer server, Socket socket) throws IOException {
this.server = server;
this.socket = socket;
this.writer = new PrintWriter(this.socket.getOutputStream());
this.reader = new BufferedReader(new InputStreamReader(socket.getInputStream()));
}
synchronized public void write(String string) throws IOException {
writer.write(string);
writer.flush();
}
public void close() {
this.writer.close();
try {
this.reader.close();
} catch (IOException e) {
}
try {
this.socket.close();
} catch (IOException e) {
}
}
#Override
public void run() {
System.out.println("Client Waiting");
String inString = null;
try {
while ((inString = this.reader.readLine()) != null) {
this.server.writeToAllClients(inString + "\n");
System.out.println(inString);
}
} catch (IOException e1) {
}
server.removeClient(this);
this.close();
System.out.println("Client Closed");
}
}
}
In your handler:
while((s = reader.readLine()) != null) {
writer.write(s + "\n");
writer.flush();
System.out.println(s);
}
You are only writing the string back to the sender, not to all connected sockets
I am very new to sockets and was hoping someone could help me. I had something working but it was not sending information very quickly so i have refactored and now cannot get back to anything which works. The issue seems to be that only the first message that is published is read and then the receiver sits on client = listener.accept(); even though im pretty sure the sender is still sending messages
Can anyone see what i might be doing wrong here please?
Thanks
public class Sender {
Socket server = null;
DataInputStream inp = null;
PrintStream outp = null;
public Sender(){
server = new Socket("127.0.0.1" , 3456);
outp = new PrintStream(server.getOutputStream());
}
private void connectAndSendToServer(String message) {
outp = new PrintStream(server.getOutputStream());
outp.print(message + "\n");
outp.flush();
}
}
Receiver class
public class Receive{
public String receiveMessage(int port) {
String message= null;
ServerSocket listener = null;
Socket client = null;
try{
listener = new ServerSocket(port);
client = listener.accept();
BufferedReader br = new BufferedReader(new InputStreamReader(client.getInputStream()));
return br.readLine();
}
...
finally{
try {
if(client!=null && listener!=null){
client.close();
listener.close();
}
}
catch (IOException e) {
}
}
return message;
}
}
This because a ServerSocket is used as an entry point for a normal Socket. accept() is a blocking operation that is usually done on a different thread compared to the one that receives/sends data to normal Socket. It sits there and waits for a new connection to spawn a new Socket which is then used for data.
This means that while receiving messages you should call just readLine() to read from the specific Socket. Having an accept inside the receiveMessage is wrong just because it's a different operation and it's even blocking.
Socket socket = serverSocket.accept();
ClientThread thread = new ClientThread(socket);
class ClientThread extends Thread {
Socket socket;
public void run() {
while (!closed) {
String line = reader.readLine();
...
}
}
You don't need to have a thread for every client though, but you need at least two for sure if you want to make your server accept a number of connections greater than 1.
You are not using ServerSocket correctly. You shouldn't create a new instance for every message but use it as a data member maybe and run an infinite loop to get a new client socket connection. Because you create it locally, the socket is closed since the object is no longer used and referenced (and so GC'ed), when you return from the method.
Something like (< condition met > is pseudo-code defines your condition to accept new connections):
while(< condition met >) {
try {
client = listener.accept();
BufferedReader br = new BufferedReader(new InputStreamReader(client.getInputStream()));
String str = br.readLine();
//do something with str
} finally {
//close client socket
}
}
Better approach will be to handle client socket in a different thread so the main thread is back to accept while you can do anything with the client socket in parallel.
Try this basic Chatting Server written by me. This server simply keeps running in loop and broadcast the message send by the clients to all the other clients associated with this server.
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.OutputStream;
import java.io.PrintWriter;
import java.net.ServerSocket;
import java.net.Socket;
import java.util.ArrayList;
public class Server {
// ///----------------------------------------Instance Variable Fields
ServerSocket ss = null;
Socket incoming = null;
// ///----------------------------------------Instance Variable Fields
// ///---------------------------------------- static Variable Fields
public static ArrayList<Socket> socList = new ArrayList<Socket>();
// ///---------------------------------------- static Variable Fields
public void go() {
try {
ss = new ServerSocket(25005);
while (true) {
incoming = ss.accept();
socList.add(incoming);
System.out.println("Incoming: " + incoming);
new Thread(new ClientHandleKaro(incoming)).start();
}
} catch (IOException e) {
e.printStackTrace();
} finally {
try {
ss.close();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
class ClientHandleKaro implements Runnable {
InputStream is = null;
OutputStream os = null;
InputStreamReader isr = null;
BufferedReader br = null;
PrintWriter pw = null;
boolean isDone = false;
Socket sInThread = null;
public ClientHandleKaro(Socket sxxx) {
this.sInThread = sxxx;
}
#Override
public void run() {
if (sInThread.isConnected()) {
System.out.println("Welcamu Clienta");
System.out.println(socList);
}
try {
is = sInThread.getInputStream();
System.out.println("IS: " + is);
isr = new InputStreamReader(is);
br = new BufferedReader(isr);
os = sInThread.getOutputStream();
pw = new PrintWriter(os, true);
String s = new String();
while ((!isDone) && (s = br.readLine()) != null) {
String[] asx = s.split("-");
System.out.println("On Console: " + s);
// pw.println(s);
Thread tx = new Thread(new ReplyKaroToClient(s,
this.sInThread));
tx.start();
if (asx[1].trim().equalsIgnoreCase("BYE")) {
System.out.println("I am inside Bye");
isDone = true;
}
}
} catch (IOException e) {
System.out.println("Thanks for Chatting.....");
} finally {
try {
Thread tiku = new Thread(new ByeByeKarDo(sInThread));
tiku.start();
try {
tiku.join();
} catch (InterruptedException e) {
e.printStackTrace();
}
System.out.println("Accha to hum Chalte hain !!!");
System.out.println(socList);
br.close();
pw.close();
sInThread.close();
} catch (IOException e) {
}
}
}
}
class ReplyKaroToClient implements Runnable {
public String mString;
public Socket mSocket;
public ReplyKaroToClient(String s, Socket sIn) {
this.mString = s;
this.mSocket = sIn;
}
#Override
public void run() {
for (Socket sRaW : socList) {
if (mSocket.equals(sRaW)) {
System.out.println("Mai same hun");
continue;
} else {
try {
new PrintWriter(sRaW.getOutputStream(), true)
.println(mString);
} catch (IOException e) {
System.out.println("Its in Catch");
}
}
}
}
}
class ByeByeKarDo implements Runnable {
Socket inCom;
public ByeByeKarDo(Socket si) {
this.inCom = si;
}
#Override
public void run() {
try {
new PrintWriter(inCom.getOutputStream(), true)
.println("You have Logged Out of Server... Thanks for your Visit");
} catch (IOException e) {
e.printStackTrace();
}
}
}
public static void main(String[] args) {
new Server().go();
}
}
I'm trying to write a little SocketServer and a fitting ClientApplet. The connection works (I echo out incoming/closing connections), but the server does not get any InputStream.
I just can't fix the problem and feel a bit lost :/
The complete project is here.
Here is the responsible part of my server:
MessageService.java
public class MessageService implements Runnable {
private final Socket client;
private final ServerSocket serverSocket;
MessageService(ServerSocket serverSocket, Socket client) {
this.client = client;
this.serverSocket = serverSocket;
}
#Override
public void run() {
PrintWriter out = null;
BufferedReader in = null;
String clientName = client.getInetAddress().toString();
try {
out = new PrintWriter(new OutputStreamWriter(client.getOutputStream()));
in = new BufferedReader(new InputStreamReader(client.getInputStream()));
String line;
System.out.println("Waiting for "+clientName);
/* HERE I TRY TO GET THE STREAM */
while((line = in.readLine()) != null) {
System.out.println(clientName + ": " + line);
out.println(line);
out.flush();
}
}
catch (IOException e) {
System.out.println("Server/MessageService: IOException");
}
finally {
if(!client.isClosed()) {
System.out.println("Server: Client disconnected");
try {
client.close();
}
catch (IOException e) {}
}
}
}
}
Part of Client
QueueOut.java
public class QueueOut extends Thread {
Socket socket;
public ConcurrentLinkedQueue<String> queue;
PrintWriter out;
public QueueOut(Socket socket) {
super();
this.socket = socket;
this.queue = new ConcurrentLinkedQueue<String>();
System.out.print("OutputQueue started");
}
#Override
public void start() {
try {
out = new PrintWriter(new OutputStreamWriter(socket.getOutputStream()));
System.out.println("Running outputqueue");
while(true) {
if(this.queue.size() > 0) {
String message = this.queue.poll();
System.out.println("Sending "+message);
out.println(message+"\n");
}
}
}
catch (IOException ex) {
System.out.println("Outputqueue: IOException");
}
}
public synchronized void add(String msg) {
this.queue.add(msg);
}
}
I have reduced my post to the (as i think) necessary parts :)
Try getting your input stream before you get the output stream, even though you're not using it, you should match the inverse order on your client and your server (as discussed in another similar threads).
Edit:
Also see Socket programming
Good Luck!