I am writing a Server/Client chat where basically Multiple Clients connected to One Server. One client send a message to server Then all other Clients will get the same message. For example: Client A, B, C Connected to A same Server. Client A send Message To Server, Server then will send the same message to client B and C but exclude Client A.
I'm stuck at part where Server send out the message to all other clients.
Below is the code, I'm just a Java beginner so any help with the code will be much appreciate.
ServerSide
public class ServerP2P extends Thread{
private ServerSocket server = null;
private Socket clientSocket = null;
private ArrayList<ServerThread> clientThreadList = new ArrayList<>();
private int maxClient = 4;
private int port = 9990;
boolean listening = true;
public ServerP2P(){
try{
server = new ServerSocket(port);
}catch(IOException e){
e.printStackTrace();
return;
}
System.out.println("Server with Port "+port+" is Up and Running");
}
public void run(){
System.out.println("Room Chat Is Up");
while(listening){
for(int i = 0;i<clientThreadList.size();i++){
if(!clientThreadList.get(i).getConneection()){
System.out.println(clientThreadList.get(i)+" is removing from server because there is no conntection");
clientThreadList.remove(i);
}
}
try{
clientSocket = server.accept();
}catch(Exception e){
e.printStackTrace();
}
System.out.println("User with IP "+clientSocket.getInetAddress()+" Has Connected to Server");
clientThreadList.add(new ServerThread(clientSocket));
try{
Thread.sleep(200);
}catch(Exception e){
e.printStackTrace();
}
}
}
public ArrayList<ServerThread> listOFClient(){
return clientThreadList;
}
public static void main(String[] args){
ServerP2P server = new ServerP2P();
server.start();
}
}
ServerThread
public class ServerThread{
private Socket clientSocket;
private boolean connected;
private Incomming incommingData;
String msg = null;
private class Incomming extends Thread{
private DataInputStream input;
public void run(){
try{
input = new DataInputStream(clientSocket.getInputStream());
}catch(IOException e){
e.printStackTrace();
return;
}
System.out.println("User with IP "+clientSocket.getInetAddress()+" has connected");
while(true){
try{
Thread.sleep(200);
int msgSize = input.readInt();
byte[] msgByte = new byte[msgSize];
for(int i = 0; i < msgSize ; i++){
msgByte[i] = input.readByte();
}
msg = new String(msgByte);
System.out.println(msg);
}catch(Exception e){
e.printStackTrace();
}
}
}
}
public ServerThread(Socket newClientSocket){
this.clientSocket = newClientSocket;
connected = true;
incommingData = new Incomming();
incommingData.start();
}
public boolean getConneection(){
return connected;
}
public void closeConnection(){
try{
connected = false;
clientSocket.close();
}catch(Exception e){
e.printStackTrace();
}
}
}
ClientSide
public class ClientP2P{
private Socket serverSocket = null;;
private DataOutputStream output = null;
BufferedReader reader = new BufferedReader(new InputStreamReader(
System.in));
public static void main(String[] args) {
ClientP2P client = new ClientP2P();
client.startConnect();;
}
public void startConnect(){
int port = 9990;
try {
serverSocket = new Socket("localhost", port);
System.out.println(serverSocket.isBound());
output = new DataOutputStream(serverSocket.getOutputStream());
System.out.println("Please Enter Your name: ");
String nameClient = reader.readLine();
output.writeInt(nameClient.length());
output.writeBytes(nameClient);
} catch (Exception e) {
e.printStackTrace();
}
System.out.println("You Are Connected");
System.out.println("Chat Can Start");
sendText();
}
public void sendText(){
try {
while (true) {
System.out.println("Type Message: ");
String msg = reader.readLine();
output.writeInt(msg.length());
output.writeBytes(msg);
System.out.println("Message sent");
recivedText();
}
} catch (Exception e) {
e.printStackTrace();
}
}
public void recivedText(){
try{
DataInputStream input = new DataInputStream(serverSocket.getInputStream());
int textSize = 0;
while(input.available() != 0){
byte[] byteString = new byte[textSize];
for(int i = 0; i < textSize;i++){
byteString[i] = input.readByte();
}
String txtServer = new String(byteString);
System.out.println(txtServer);
textSize = 0;
}
sendText();
}catch(Exception e){
e.printStackTrace();
}
}
}
Thanks For Your Time Guys.
Your ServerThread receives the messages and you want to send them to all other clients. One way you could achieve is to have the clients register themselves with the Server (this would help in the server not knowing the clients when it starts, which ideally should be the case). In your ServerThread, get a list of available clients from the server and loop through them and send the message to each one of them.
Use ObserverDesign pattern to hold the list of all your buddy/user to whom you wish to send message. Use HashMap to maintain a list of all the observer and its socket. Once the message is received, you retrieve the sockets of each user and write the same message on each socket.
Related
So I've been making a chatroom based off a single server, where clients can connect and talk in the chatroom. At the moment each client can speak to the server and the server returns what the client has said. But I've been struggling to broadcast a single client message to all clients.
I stored all socket connections in an ArrayList and then created a for loop to iterate through all the connections to echo a single message to all the connected clients. Unfortunately my code is not working and I can't understand why. Here's my code:
Handler code:
public class Handler implements Runnable {
private Socket client;
String message = "";
public Handler(Socket client){
this.client = client;
}
#Override
public void run() {
try{
try{
ChatClient CCG = new ChatClient();
Scanner INPUT = new Scanner(client.getInputStream()); //input data from the server
PrintWriter OUT = new PrintWriter(client.getOutputStream()); //output data from the server
while(true){
if(!INPUT.hasNextLine()){ //if nothings there, end it
return;
}
message = INPUT.nextLine(); //get input
System.out.println("Client HANDLER said: "+ message);
//echo out what the client says to all the users
for(int i=1; i<= ChatServer.ConnectionArray.size(); i++){
Socket TEMP_SOCK = (Socket) ChatServer.ConnectionArray.get(i-1);
PrintWriter TEMP_OUT = new PrintWriter(TEMP_SOCK.getOutputStream());
TEMP_OUT.println(message);
TEMP_OUT.flush();
System.out.println("Sent to: " + TEMP_SOCK.getLocalAddress().getHostName()); //displyed in the console
}
}
}finally{
client.close();
}
}catch(Exception X){
X.printStackTrace();
}
}
}
EDIT: Changed client.getOutputStream() to TEMP_SOCK.getOutputStream() but still no luck :/
Server code:
public class ChatServer {
public static ServerSocket server;
public static boolean ServerOn=true;
public static ArrayList<Socket> ConnectionArray = new ArrayList<Socket>(); //holds all the connections so messages can be echoed to all the other users
public static ArrayList<String> CurrentUsers = new ArrayList<String>(); //current users
public static void main(String[] args){
//ExecutorService executor = Executors.newFixedThreadPool(30); //number of clients allowed to join the server
try {
server = new ServerSocket(14001);
System.out.println("Server started!");
System.out.println("Waiting for clients to connect...");
while(true){
try {
//ChatClient chatClient = new ChatClient();
Socket client = server.accept();
ConnectionArray.add(client); //add socket to connection array and allows multiple users to enter server
System.out.println(ConnectionArray);
//CurrentUsers.add(chatClient.user);
//System.out.println("Current users: "+CurrentUsers);
System.out.println("Client connected from: " + client.getLocalAddress().getHostName()); //gets their ip address and local host name
Thread thread = new Thread(new Handler(client));
thread.start();
} catch (IOException e) {
e.printStackTrace();
}
}
} catch (IOException ex) {
ex.printStackTrace();
}
}
}
Client Code:
public class ChatClient extends javax.swing.JFrame {
Socket sock;
String message;
int port = 14001;
PrintWriter write;
BufferedReader read;
String user;
ArrayList<String> usersOnline = new ArrayList();
InputStreamReader streamreader;
boolean userConnected = false;
public ChatClient() {
initComponents();
}
/*public class Incoming implements Runnable{
public void run(){
try{
sock = new Socket("localhost",14001);
write = new PrintWriter(out);
} catch (IOException ex) {
ex.printStackTrace();
}
}
}*/
public void addUser(){
onlineUsersTextArea.append(user+" \n");
usersOnline.add(user);
System.out.println(usersOnline);
}
/*public void Send(){
String bye = (user + ": :Disconnect");
try{
write.println(bye);
write.flush();
}catch(Exception ex){
chatTextArea.append("Could not send disconnect message. \n");
}
}*/
public void userDisconnected(){
chatTextArea.append(user + " has disconnected.\n");
}
public void Disconnect(){
try{
chatTextArea.append("Disconnected.\n"); // Notify user that they have disconnected
write.flush();
sock.close(); // Closes the socket
System.out.println(user + " has disconnected.");
}catch(Exception e){
chatTextArea.append("Failure to disconnect.\n");
}
userConnected = false;
onlineUsersTextArea.setText(""); // Remove name from online users
usernameInputField.setEditable(true); // Allows a username to be created
}
private void connectButtonActionPerformed(java.awt.event.ActionEvent evt) {
if(userConnected == false){
user = usernameInputField.getText();
usernameInputField.setEditable(false);
try{
sock = new Socket("localhost", port);
InputStreamReader sReader = new InputStreamReader(sock.getInputStream());
write = new PrintWriter(sock.getOutputStream());
read = new BufferedReader(sReader);
addUser();
chatTextArea.append(user + " has connected. \n");
write.println(user+" has connected."); // Display username of client when connection is established
write.flush(); // Flushes the stream
userConnected = true;
} catch (IOException ex) {
chatTextArea.append("Failed to connect.\n");
usernameInputField.setEditable(true);
ex.printStackTrace();
}
}else if(userConnected == true){
chatTextArea.append("You are already connected. \n");
}
}
private void disconnectButtonActionPerformed(java.awt.event.ActionEvent evt) {
Disconnect();
userDisconnected();
}
private void sendButtonActionPerformed(java.awt.event.ActionEvent evt) {
String nothing = "";
if((userInputTextArea.getText()).equals(nothing)){
userInputTextArea.setText("");
userInputTextArea.requestFocus();
}else{
try{
chatTextArea.append(user + ": " + userInputTextArea.getText()+" \n");
write.println(user + ": " + userInputTextArea.getText());
write.flush();
}catch(Exception ex){
chatTextArea.append("Message failed to send. \n");
}
userInputTextArea.setText("");
userInputTextArea.requestFocus();
}
userInputTextArea.setText("");
userInputTextArea.requestFocus();
}
private void usernameInputFieldActionPerformed(java.awt.event.ActionEvent evt) {
}
/**
* #param args the command line arguments
*/
public static void main(String args[]) {
java.awt.EventQueue.invokeLater(new Runnable() {
public void run() {
new ChatClient().setVisible(true);
}
});
}
}
My for loop is in the Handler class. I'm not understanding why the message isn't being sent out to the clients. The TEMP_SOCK (temporary socket) should work (I think) but the server only receives the messages but doesn't echo them.
Any help on how to go about this would be really appreciated! Thank you :)
PrintWriter TEMP_OUT = new PrintWriter(client.getOutputStream()); means you're always sending to the same client, you should use PrintWriter TEMP_OUT = new PrintWriter(TEMP_SOCK.getOutputStream());
I'm trying to make a threaded server client messaging application in java. I'm having trouble sending a message that a client sent to every other client connected to the server. I added all connected threads to an array list so when a message is sent I can iterate over the list and send it to all the clients but this doesn't seem to be working. What am I doing wrong here?
When one client is connected it works perfectly the server echos everything the client says. When two clients are connected only the client that sent the message gets the message. If that same client though send another message the server seems to get hung up and no messages get echoed.
Threaded Server Code
import java.io.*;
import java.net.*;
import java.util.*;
public class ThreadedSever
{
private static final int port=5000;
ArrayList<ServerThread> clientList = new ArrayList<ServerThread>();
//Threaded Server
public ThreadedSever(){
System.out.println("A multi-threaded server has started...");
ServerSocket serverSocket = null;
try {
serverSocket = new ServerSocket(port);
}catch(Exception e){
System.out.println("Could not create a server socket: " + e);
}
//Chat with the client until breaks connection or says bye
try{
while(true){
System.out.println("Waiting for client communication");
Socket currentSocket = serverSocket.accept();
//Create a new thread to deal with this connection
clientList.add(new ServerThread(currentSocket));
System.out.println(clientList);
}
}catch(Exception e){
System.out.println("Fatal Server Error!");
}
}
//Inner class to handle individual commincation
private class ServerThread extends Thread{
//Possible add name to then get private messages
private Socket sock;
private DataInputStream in = null;
private DataOutputStream out = null;
public ServerThread(Socket sock){
try{
this.sock = sock;
in = new DataInputStream(this.sock.getInputStream());
out = new DataOutputStream(this.sock.getOutputStream());
System.out.print("New client connection established");
out.writeUTF("Type bye to exit, otherwise, prepare to be echoed");
start();
}catch(Exception e){
System.out.println("Oops");
}
}
public void run(){
try{
String what = new String("");
while(!what.toLowerCase().equals("bye")){
what = in.readUTF();
echoMessage(what);
}
}catch(Exception e){
System.out.println("Connection to current client has been broken");
}
finally{
try{
sock.close();
}catch(Exception e){
System.out.println("Error socket could not be closed");
}
}
}
public void echoMessage(String what){
try{
for (ServerThread Thread: clientList) {
in = Thread.in;
out = Thread.out;
System.out.println("Client told me: " + what);
out.writeUTF(what);
}
}catch(Exception e){
}
}
}
public static void main(){
new ThreadedSever();
}
}
Client Code
import java.io.*;
import java.net.*;
public class simpleClient
{
private static final int port= 5000;
private static String server = "localhost";
private static Socket socket = null;
private static DataInputStream input = null;
private static DataOutputStream output = null;
private static InputStreamReader inReader = null;
private static BufferedReader stdin = null;
public static void main(){
try{
socket = new Socket(server, port);
}catch(UnknownHostException e){
System.err.println("Unknow IP address for server");
System.exit(-1);
}
catch(IOException e){
System.err.println("No server found at specified port");
System.exit(-1);
}
catch(Exception e){
System.err.println("Something happened!");
System.exit(-1);
}
try{
input = new DataInputStream(socket.getInputStream());
output = new DataOutputStream(socket.getOutputStream());
inReader = new InputStreamReader(System.in);
stdin = new BufferedReader(inReader);
String what = new String("");
String response;
while(!what.toLowerCase().equals("bye")){
// Expect something from the server and output it when it arrives
response = input.readUTF();
System.out.println("Server said \"" + response + "\"");
//Read a line from the user and send it to the server
what = stdin.readLine();
output.writeUTF(what);
}
}
catch(IOException e){
System.err.println("Broken connection with server");
System.exit(-1);
}
}
}
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();
}
Trying to build a simple multi-threaded chat server that runs via command prompt. The clients do connect to the server and the server will hold multiple clients, however when trying to send messages from one client to the other, or even notifying a client of another user logging in, nothing comes up on the client command prompt.
public class Server {
private static ServerSocket servSock;
private static Socket clientSock;
private static ArrayList<ClientThread> clientList;
private static int IDcount = 0;
public static void main(String args[]){
// Get command line arguments.
if (args.length != 3) {
System.out.println("Required arguments: server port, block duration, timeout");
return;
}
int port = Integer.parseInt(args[0]);
int blockDur = Integer.parseInt(args[1]);
int timeout = Integer.parseInt(args[2]);
try{
servSock = new ServerSocket(port);
clientList = new ArrayList<ClientThread>();
}
catch(IOException ex){
System.err.println(ex);
}
while (true) {
try {
clientSock = servSock.accept();
ClientThread thread = new ClientThread(clientSock);
clientList.add(thread);
thread.start();
} catch (IOException e) {
System.out.println(e);
}
}
}
private synchronized static void broadcast(String msg){
System.out.print(msg);
for(int i = 0; i < clientList.size(); i++){
ClientThread client = clientList.get(i);
client.send(msg);
}
}
synchronized static void unlist(int id){
for(int i = 0; i < clientList.size(); i++){
ClientThread thread = clientList.get(i);
if(thread.id == id){
clientList.remove(i);
return;
}
}
}
static class ClientThread extends Thread {
Socket sock;
BufferedReader tIn;
PrintWriter tOut;
int id;
String username;
String msg;
ClientThread(Socket sock){
id = IDcount++;
this.sock = sock;
try{
tIn = new BufferedReader(new InputStreamReader(sock.getInputStream()));
tOut = new PrintWriter(sock.getOutputStream());
username = tIn.readLine();
broadcast(username + " logged in");
}
catch(IOException ex){
System.err.println(ex);
}
}
public void run(){
boolean loggedIn = true;
while(loggedIn){
try{
msg = tIn.readLine();
}
catch (IOException ex){
System.err.println(ex);
}
String[] parts = msg.split("\\s",2);
String type = parts[0];
Client code is similar
public class Client{
private static Socket clientSock;
private static BufferedReader in;
private static PrintWriter out;
private static Scanner scan;
public static void main(String[] args) throws IOException {
if (args.length != 2) {
System.out.println("Required arguments: server IP, server port");
return;
}
String host = args[0];
int port = Integer.parseInt(args[1]);
clientSock = new Socket(host, port);
in = new BufferedReader(new InputStreamReader(clientSock.getInputStream()));
out = new PrintWriter(clientSock.getOutputStream());
scan = new Scanner(System.in);
new ListenFromServer().start();
boolean online = true;
System.out.println("Enter your username:");
String username = scan.nextLine();
out.println(username);
while(online){
System.out.println("> ");
String msg = scan.nextLine();
String[] parts = msg.split("\\s");
String type = parts[0];
send(msg);
if(type.equalsIgnoreCase("logout")){
online = false;
}
}
logoff();
}
static void send(String msg) throws IOException{
out.println(msg);
}
private static void logoff() throws IOException{
in.close();
out.close();
scan.close();
clientSock.close();
}
static class ListenFromServer extends Thread{
public void run(){
while(true){
try{
String msg = in.readLine();
System.out.println(msg);
}
catch(IOException ex){
System.err.println(ex);
}
}
}
}
}
When you send data with PrintWriter.println(), data write to buffer. You must call PrintWriter.flush() after println to send data to or from the server immediately.
And when you call username = tIn.readLine(); in ClientThread constructor, you block main-thread, because constructor calls in main-thread. So, while connected user won't send username, other clients can't connect.
I'm trying to create a java push server model for testing on my own machine, this won't be used to connect external clients as the server and client will be on the same machine. After the client connects on the port specified by he/she, they should send a message of their choice that will be sent back to them, and any other clients connected to the same port.
The problem I'm having is i receive a java.net.ConnectException: Connection refused: connect when this is attempted. Below is the client and the server.
Edit: I've taken the time to ensure that the necessary ports are open too, and even disabled my firewall, but to no avail.
Server:
class MainServer {
// port that oir server is going to operate on
final static int port = 1234;
public static void main(String[] args) {
// this is going to model the server for the moment
System.out.println("Server has been started...");
Buffer<Messages> store = new Buffer<Messages>(10);
new Writer(store).start();
try {
ServerSocket serve = new ServerSocket(port);
while(true) {
// wait for server request
Socket socket = serve.accept();
// start thread to service request
new ServerThread(socket,store).start();
}
} catch(IOException e) {e.printStackTrace();}
}
}
class ServerThread extends Thread {
Socket socket;
Buffer<Messages> buffer;
public ServerThread(Socket s, Buffer<Messages> b) {
socket = s;buffer = b;
}
public void run() {
try {
DataInputStream in = new DataInputStream(socket.getInputStream());
int port = in.readInt();
System.out.println("Port: "+port);
Messages ms = new Messages(port);
// Read message as string from user
String message = in.readUTF();
int k = in.readInt();
while(k != -1) {
// Add message to array
// read next message
ms.add(message);
message = in.readUTF();
}
// close connection
socket.close();
// add message to buffer
buffer.put(ms);
} catch(IOException e) {e.printStackTrace();}
}
}
class Writer extends Thread {
Buffer<Messages> buffer;
public Writer(Buffer<Messages> m) {buffer = m;}
public void run() {
while(true) {
Messages dp = buffer.get();
dp.write();
}
}
}
class Buffer <E> {
/**
* Producer & Consumer Buffer
*/
private int max;
private int size = 0;
private ArrayList<E> buffer;
private Semaphore empty; //control consumer
private Semaphore full; // control producer
private Lock lock = new ReentrantLock();
public Buffer(int s) {
buffer = new ArrayList<E>();
max = s;
empty = new Semaphore(0);
full = new Semaphore(max);
}
// add data to our array
public void put(E x) {
try {
full.acquire();
} catch(InterruptedException e) {}
// sync update to buffer
lock.lock();
try {
buffer.add(x);
size++;
empty.release();
} finally {lock.unlock();}
}
public E get() {
try {
empty.acquire();
} catch(InterruptedException e) {}
// sync uodate on buffer
lock.lock();
try {
E temp = buffer.get(0);
buffer.remove(0);
size--;
full.release();
return temp;
} finally {lock.unlock();}
}
}
final class Messages {
private final int port;
private final ArrayList<String> data = new ArrayList<String>();
public Messages(int p) {port = p;}
void add(String message) {
data.add(message);
}
void write() {
try {
Socket socket;
socket = new Socket(InetAddress.getLocalHost(),port);
DataOutputStream out = new DataOutputStream(socket.getOutputStream());
// write message
out.write(data.size());
for(String k : data) {out.writeUTF(k);}
out.flush();
socket.close();
} catch(IOException e) {e.printStackTrace();}
}
}
Client:
class Client {
final static int nPort = 1234;
static int serverPort;
public static void main(String[] args) {
// this class and those present in it
// will model the client for assignment 8
Scanner in = new Scanner(System.in);
System.out.println("Please enter the messageboard number: ");
serverPort = in.nextInt();
System.out.println("Please type your message: ");
String msg = in.next();
Listener lis = new Listener(serverPort);
lis.start();
boolean go = true;
while(go) {
try {
Thread.sleep(2000);
} catch(InterruptedException e) {}
write(serverPort, msg);
System.out.println("Continue: 0/1");
int x = in.nextInt();
if(x == 0)go = false;
}
System.exit(0);
}
static void write(int port, String msg) {
try {
Socket socket;
socket = new Socket(InetAddress.getLocalHost(),port);
DataOutputStream out = new DataOutputStream(socket.getOutputStream());
// send message to port
out.writeInt(port);
out.writeUTF(msg);
// write sentinal after message has been written and close socket
out.writeInt(-1);
out.flush();
socket.close();
} catch(IOException e) {System.out.println(e);}
}
}
class Listener extends Thread {
private int port;
volatile boolean go;
public Listener(int p) {p = port;}
public void run() {
try {
ServerSocket serversock = new ServerSocket(port);
while(go) {
Socket socket = serversock.accept();
DataInputStream in = new DataInputStream(socket.getInputStream());
// Read the message
while(in.available() > 0) {
String k = in.readUTF();
System.out.print(k+" ");
}
System.out.println();
socket.close();
}
} catch(IOException e) {go = false;}
}
}
Turns out i had a wrong assignment in my Listener class. I had p = port instead of port = p.
Solved. Through my own stupidity.
The hostname you are connecting to is localhost so you are assuming the server is on the same machine. If you need to connect to a different machine, you need to specify the host you want it to connect to.
Try changing socket = new Socket(InetAddress.getLocalHost(),port);
to
socket = new Socket(*IP OF SERVER (127.0.0.1 if same machine)*, port);