I'm writing a chat room server which takes message from a chat client and broadcasts out the message to all users. This is an exercise from a book called An Introduction to Network Programming with Java: Java 7 Compatible with which I'm self-teaching Java networking basics. I wrote a GUI frontend for the chat room and implemented the server backend, following examples from the code in the book. However, when I tested the code with chat clients, the server seemed unable to receive clients' data. I can't figure out why. The code for the chat room (here it was made in command line mode for test purpose) and the client is as followings. Thank you.
// code for the server backend, problem seems to be lie in here.
/**
* The multiecho server itself
*/
package channelEchoServer;
import java.net.*;
import java.io.*;
import java.nio.*;
import java.nio.channels.*;
import java.util.*;
public class MultiEchoServerNIO {
private static ServerSocketChannel serverSocketChannel;
private static final int PORT = 1234;
private static Selector selector;
private static Vector<SocketChannel> socketChannelVec;
private static Vector<ChatUser> allUsers;
public static final int CAPACITY = 20;
public static final int BUFFER_SIZE = 2048;
public static final String NEW_LINE = System.lineSeparator();
public static void main(String[] args) {
ServerSocket serverSocket = null;
try {
serverSocketChannel = ServerSocketChannel.open();
serverSocketChannel.configureBlocking(false);
serverSocket = serverSocketChannel.socket();
InetSocketAddress netAddress = new InetSocketAddress(PORT);
serverSocket.bind(netAddress);
selector = Selector.open();
serverSocketChannel.register(selector, SelectionKey.OP_ACCEPT);
}
catch (IOException ioEx) {
ioEx.printStackTrace();
System.exit(1);
}
socketChannelVec = new Vector<>(CAPACITY);
allUsers = new Vector<>(CAPACITY);
System.out.println("Server is opened ...");
processConnections();
}
private static void processConnections () {
do {
try {
int numKeys = selector.select();
System.out.println(numKeys + " keys selected.");
if (numKeys > 0) {
Set eventKeys = selector.selectedKeys();
Iterator keyCycler = eventKeys.iterator();
while (keyCycler.hasNext()) {
SelectionKey key = (SelectionKey)keyCycler.next();
int keyOps = key.readyOps();
if ((keyOps & SelectionKey.OP_ACCEPT) == SelectionKey.OP_ACCEPT) {
acceptConnection(key);
continue;
}
if ((keyOps & SelectionKey.OP_READ) == SelectionKey.OP_READ) {
acceptData(key);
}
}
}
}
catch (IOException ioEx) {
ioEx.printStackTrace();
System.exit(1);
}
} while (true);
}
private static void acceptConnection (SelectionKey key) throws IOException {
SocketChannel socketChannel;
Socket socket;
socketChannel = serverSocketChannel.accept();
socketChannel.configureBlocking(false);
socket = socketChannel.socket();
System.out.println("Connection on " + socket + ".");
socketChannel.register(selector, SelectionKey.OP_READ);
socketChannelVec.add(socketChannel);
selector.selectedKeys().remove(key);
}
private static void acceptData (SelectionKey key) throws IOException {
SocketChannel socketChannel;
Socket socket;
ByteBuffer buffer = ByteBuffer.allocate(BUFFER_SIZE);
socketChannel = (SocketChannel) key.channel();
buffer.clear();
int numBytes = socketChannel.read(buffer);
socket = socketChannel.socket();
if (numBytes == -1) {
key.cancel();
closeSocket(socket);
}
else {
String chatName = null;
byte[] byteArray = buffer.array();
if (byteArray[0] == '#')
announceNewUser(socketChannel, buffer);
else {
for (ChatUser chatUser : allUsers)
if (chatUser.getUserSocketChannel().equals(socketChannel))
chatName = chatUser.getChatName();
broadcastMessage(chatName, buffer);
}
}
}
private static void closeSocket (Socket socket) {
try {
if (socket != null)
socket.close();
}
catch (IOException ioEx) {
System.out.println("Unable to close socket!");
}
}
public static void announceNewUser (SocketChannel userSocketChannel, ByteBuffer buffer) {
ChatUser chatUser;
byte[] byteArray = buffer.array();
int messageSize = buffer.position();
String chatName = new String(byteArray, 1, messageSize);
if (chatName.indexOf("\n") >= 0)
chatName = chatName.substring(0, chatName.indexOf("\n"));
chatUser = new ChatUser(userSocketChannel, chatName);
allUsers.add(chatUser);
if (!socketChannelVec.remove(userSocketChannel)) {
System.out.println("Can't find user!");
return;
} // we should save userSocketChannel in a chatUser instance before deleting it.
chatName = chatUser.getChatName();
System.out.println(chatName + " entered the chat room at " + new Date() + "." + NEW_LINE);
String welcomeMessage = "Welcome " + chatName + "!" + NEW_LINE;
byte[] bytes = welcomeMessage.getBytes();
buffer.clear();
for (int i = 0; i < welcomeMessage.length(); i++)
buffer.put(bytes[i]);
buffer.flip();
try {
chatUser.getUserSocketChannel().write(buffer);
}
catch (IOException ioEx) {
ioEx.printStackTrace();
}
}
public static void announceExit (String name) {
System.out.println(name + " left chat room at " + new Date() + "." + NEW_LINE);
for (ChatUser chatUser : allUsers) {
if (chatUser.getChatName().equals(name))
allUsers.remove(chatUser);
}
}
public static void broadcastMessage (String chatName, ByteBuffer buffer) {
String messagePrefix = chatName + ": ";
byte[] messagePrefixBytes = messagePrefix.getBytes();
final byte[] CR = NEW_LINE.getBytes();
try {
int messageSize = buffer.position();
byte[] messageBytes = buffer.array();
byte[] messageBytesCopy = new byte[messageSize];
String userMessage = new String(messageBytes, 0, messageSize);
if (userMessage.equals("Bye"))
announceExit(chatName);
for (int i = 0; i < messageSize; i++)
messageBytesCopy[i] = messageBytes[i];
buffer.clear();
buffer.put(messagePrefixBytes);
for (int i = 0; i < messageSize; i++)
buffer.put(messageBytesCopy[i]);
buffer.put(CR);
SocketChannel chatSocketChannel;
for (ChatUser chatUser : allUsers) {
chatSocketChannel = chatUser.getUserSocketChannel();
buffer.flip();
chatSocketChannel.write(buffer);
}
}
catch (IOException ioEx) {
ioEx.printStackTrace();
}
}
}
class ChatUser {
private SocketChannel userSocketChannel;
private String chatName;
public ChatUser (SocketChannel userSocketChannel, String chatName) {
this.userSocketChannel = userSocketChannel;
this.chatName = chatName;
}
public SocketChannel getUserSocketChannel () {
return userSocketChannel;
}
public String getChatName () {
return chatName;
}
}
// Code for a chat client for testing purpose
package multithreadEchoChatroomClientGUI;
import java.awt.*;
import java.awt.event.*;
import javax.swing.*;
import java.io.*;
import java.net.*;
import java.util.*;
public class MultithreadEchoChatroomClient1 {
private static Socket socket;
private static InetAddress host;
private static String address;
public static final int PORT = 1234;
public static void main(String[] args) {
address = JOptionPane.showInputDialog("Enter the host name or IP address:");
try {
host = InetAddress.getByName(address);
}
catch (UnknownHostException uhEx) {
JOptionPane.showMessageDialog(null, "Unknown Host!", "Error", JOptionPane.ERROR_MESSAGE);
System.exit(1);
}
try {
socket = new Socket(host, PORT);
}
catch (IOException ioEx) {
JOptionPane.showMessageDialog(null, ioEx.toString(), "Error", JOptionPane.ERROR_MESSAGE);
System.exit(1);
}
SwingUtilities.invokeLater(new Runnable () {
public void run () {
ClientFrame client = new ClientFrame(host, socket, address);
client.setTitle("Chat");
client.setSize(400, 500);
client.setVisible(true);
new Thread(client).start();
}
});
}
}
class ClientFrame extends JFrame implements Runnable {
private InetAddress host;
private String address;
private Socket socket;
private Scanner input;
private PrintWriter output;
private JMenuItem connect;
private JTextArea serverResponseArea;
private JTextArea messageArea;
private JTextField messageFiled;
private JButton sendButton;
private String serverResponse;
private String clientName;
public ClientFrame (InetAddress host, Socket socket, String address) {
this.host = host;
this.socket = socket;
this.address = address;
initFrame();
}
public void run () {
try {
input = new Scanner(socket.getInputStream());
output = new PrintWriter(socket.getOutputStream(), true);
}
catch (IOException ioEx) {
JOptionPane.showMessageDialog(this, "Cannot create input or output stream!", "Error", JOptionPane.ERROR_MESSAGE);
closeSocket();
System.exit(1);
}
do {
clientName = JOptionPane.showInputDialog("What nickname would you like to use in the chatroom?");
} while (clientName == null);
output.println("#" + clientName);
do {
serverResponse = input.nextLine();
serverResponseArea.append(serverResponse + "\n");
} while (socket.isClosed() != true);
}
private final void closeSocket () {
try {
socket.close();
}
catch (IOException ioEx) {
JOptionPane.showMessageDialog(this, "Cannot disconnect from chatroom!", "Error", JOptionPane.ERROR_MESSAGE);
}
}
private void initFrame () {
JMenuBar menuBar = createMenuBar();
setJMenuBar(menuBar);
JScrollPane responsePanel = createResponsePanel();
add(responsePanel, BorderLayout.NORTH);
JPanel messagePanel = createMessagePanel();
add(messagePanel, BorderLayout.CENTER);
//JPanel textPanel = createTextPanel();
//add(textPanel, BorderLayout.SOUTH);
addWindowListener(new WindowAdapter () {
#Override
public void windowClosing (WindowEvent we) {
if (!socket.isClosed())
closeSocket();
System.exit(0);
}
});
}
private JMenuBar createMenuBar () {
JMenuBar menuBar = new JMenuBar();
JMenu menu = new JMenu("Operations");
connect = new JMenuItem("Connect");
connect.setEnabled(false);
connect.addActionListener(new ActionListener () {
#Override
public void actionPerformed (ActionEvent event) {
try {
host = InetAddress.getByName(address);
}
catch (UnknownHostException uhEx) {
JOptionPane.showMessageDialog(null, "Unknown Host!", "Error", JOptionPane.ERROR_MESSAGE);
System.exit(1);
}
try {
socket = new Socket(host, MultithreadEchoChatroomClient1.PORT);
}
catch (IOException ioEx) {
JOptionPane.showMessageDialog(null, ioEx.toString(), "Error", JOptionPane.ERROR_MESSAGE);
}
try {
input = new Scanner(socket.getInputStream());
output = new PrintWriter(socket.getOutputStream(), true);
}
catch (IOException ioEx) {
JOptionPane.showMessageDialog(ClientFrame.this, "Cannot create input or output stream!", "Error", JOptionPane.ERROR_MESSAGE);
closeSocket();
System.exit(1);
}
output.println("#" + clientName);
serverResponse = input.nextLine();
serverResponseArea.append(serverResponse + "\n");
}
});
JMenuItem quit = new JMenuItem("Quit");
quit.addActionListener(new ActionListener() {
#Override
public void actionPerformed (ActionEvent event) {
if (!socket.isClosed())
closeSocket();
System.exit(0);
}
});
menu.add(connect);
menu.add(quit);
menuBar.add(menu);
return menuBar;
}
private JScrollPane createResponsePanel () {
serverResponseArea = new JTextArea(20, 35);
serverResponseArea.setEditable(false);
serverResponseArea.setLineWrap(true);
serverResponseArea.setWrapStyleWord(true);
serverResponseArea.setMargin(new Insets(5, 5, 5, 5));
JScrollPane scrlPane = new JScrollPane(serverResponseArea);
scrlPane.setBorder(BorderFactory.createEmptyBorder(20, 10, 10, 20));
scrlPane.setBackground(Color.yellow);
return scrlPane;
}
private JPanel createMessagePanel () {
JPanel msgPanel = new JPanel();
msgPanel.setBorder(BorderFactory.createEmptyBorder(20,10, 10, 20));
msgPanel.setBackground(Color.blue);
msgPanel.setLayout(new BoxLayout(msgPanel, BoxLayout.LINE_AXIS));
JScrollPane srlPanel = createMessageTextPanel();
msgPanel.add(srlPanel);
JButton sdButton = createSendButton();
msgPanel.add(sdButton);
return msgPanel;
}
private JScrollPane createMessageTextPanel () {
messageArea = new JTextArea(10, 35);
//messageArea.setEditable(false);
messageArea.setLineWrap(true);
messageArea.setWrapStyleWord(true);
messageArea.setMargin(new Insets(5, 5, 5, 5));
JScrollPane mtPanel = new JScrollPane(messageArea);
return mtPanel;
}
private JButton createSendButton () {
JButton button = new JButton("Send");
button.addActionListener(new ActionListener() {
#Override
public void actionPerformed (ActionEvent event) {
String message;
message = messageArea.getText();
System.out.println(message);
output.println(message);
if (message.equals("Bye")) {
closeSocket();
connect.setEnabled(true);
}
messageArea.setText("");
//serverResponse = input.nextLine();
//serverResponseArea.append(serverResponse + "\n");
}
});
return button;
}
}
Thank you again for taking so much trouble reading much code and giving suggestions!
The problem is solved according to #user207421. I should have put a remove() operation in the else {} block in the method acceptData(SelectedKey key) so that the old key associated with the socketChannel is removed from the selected key set for new incoming keys to be able to be detected.
I don't know whether my understanding of user207421's solution was right or not, but it did solve the problem for now. If anybody has any other ideas, please share your views.
Thank you again, user207421. And thank all visitors to this post for your attention.
Using code examples from stockoverflow I made a class to receive data over TCP/IP.
Class code below. It is working OK and I do receive data from other PC.
recPositions Map is build correctly. After transmission is finished I can display all data I received using getRecPositions()
This thread is started in other class that build simple HMI screen.
Thread runs and display data received from other PC.
Problem is I would like to access same data in MainWindow class (HMI)
but it always show that nothing was received.
Class MainWindow below (not all of it since there is lots of useless pushbuttons and so on)
At the very bottom I have pushbutton that should display how many positions were recorded (elements in Map) but it always show 0.
Code snippet from push button update.
System.out.println(dataServer.getRecPositions().size())
So at some point I am doing something wrong.
Thread starts and runs and I can see incoming positions. At some point after I received "EOT" I display received positions stored in Map. But when I tried to display the size of Map in main window it always show 0.
/*
* Simple data server for receiving string data from IIWA robot
*/
public class SimpleDataServer implements Runnable {
Map<Integer, String> recPositions = new HashMap<>();
Server1Connection oneconnection;
ServerSocket echoServer = null;
Socket clientSocket = null;
int port;
boolean reset = false;
public SimpleDataServer( int port ) {
this.port = port;
}
public void stopServer() {
System.out.println( "Simple data server stopped" );
}
public void startServer() {
// Try to open a server socket on the given port
// Note that we can't choose a port less than 1024 if we are not
// privileged users (root)
try {
echoServer = new ServerSocket(port);
}
catch (IOException e) {
System.out.println(e);
}
System.out.println( "Waiting for connections. Only one connection is allowed." );
// Create a socket object from the ServerSocket to listen and accept connections.
// Use Server1Connection to process the connection.
while ( true ) {
try {
clientSocket = echoServer.accept();
oneconnection = new Server1Connection(clientSocket, this);
oneconnection.run();
if(isReset()) {
setReset(false);
System.out.println("Recording finished");
System.out.println("DEBUG:" + this.getRecPositions().size() + " positions recorded: " + this.getRecPositions());
}
}
catch (IOException e) {
System.out.println(e);
}
}
}
#Override
public void run() {
int port = this.port;
SimpleDataServer server = new SimpleDataServer( port );
server.startServer();
}
public Map<Integer, String> getRecPositions() {
return recPositions;
}
public void setRecPositions(Map<Integer, String> recPositions) {
this.recPositions = recPositions;
}
public boolean isReset() {
return reset;
}
public void setReset(boolean reset) {
this.reset = reset;
}
}
class Server1Connection {
BufferedReader is;
PrintStream os;
Socket clientSocket;
SimpleDataServer server;
public Server1Connection(Socket clientSocket, SimpleDataServer server) {
this.clientSocket = clientSocket;
this.server = server;
System.out.println( "Connection established with: " + clientSocket );
try {
is = new BufferedReader(new InputStreamReader(clientSocket.getInputStream()));
os = new PrintStream(clientSocket.getOutputStream());
} catch (IOException e) {
System.out.println(e);
}
}
public Map<Integer, String> getPositions() {
return server.getRecPositions();
}
public void run() {
String line; //whole line recevied
String segment = null; //single segment from line using comma delimiter
List<String> stringsList;
try {
boolean serverStop = false;
//server runs here
while (true)
{
line = is.readLine();
System.out.println( "DEBUG Server Received: " + line );
//check is string is not empty
if (line.equals(null)) {
System.err.println("Empty String received");
break;
}
stringsList = new ArrayList<String>(Arrays.asList(line.split(";")));
if (!stringsList.isEmpty()) {
stringsList.set(0, stringsList.get(0).replaceAll("\\s+",""));
stringsList.set((stringsList.size()-1), stringsList.get(stringsList.size()-1).replaceAll("\\s+",""));
String lastSegment = stringsList.get((stringsList.size()-1));
if (lastSegment.equals("ETX") || lastSegment.equals("EOT")) {
switch (stringsList.get(0)) {
case "MSG":
stringsList.remove(0);
stringsList.remove(stringsList.size()-1);
System.out.println("Message: " + stringsList.toString());
break;
case "POS":
// for (String blah : stringsList) {
// System.out.println("DEBUG" + blah);
// }
iiwaPosfromString iiwaPos = new iiwaPosfromString(stringsList.get(1), stringsList.get(2));
System.out.println("DEBUG Position number: " + iiwaPos.posNum + " ; " + iiwaPos.toString());
if (iiwaPos.getPosNum() > 0) {
server.getRecPositions().put(iiwaPos.getPosNum(), iiwaPos.toString());
}
break;
case "EOT":
case "EXT":
//ignore handled later
break;
default:
System.err.println("Ausgebombt!");
break;
}
}
//ETX End Of Text - dump data to screen - close current connection
if(lastSegment.equals("ETX")) {
System.out.println("End of Text received");
break;
}
//EOT End Of Transmission - shuts down server
if(lastSegment.equals("EOT")) {
System.out.println("End of Transmission received");
serverStop = true;
server.setReset(true);
break;
}
System.err.println("No correct end string!");
try {
Thread.sleep(500);
} catch (InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
break;
} else {
System.out.println("Empty String received");
break;
}
}
System.out.println( "Connection closed." );
is.close();
os.close();
clientSocket.close();
if ( serverStop ) server.stopServer();
} catch (IOException e) {
System.out.println(e);
}
}
public class iiwaPosfromString {
private double posX;
private double posY;
private double posZ;
private double posA;
private double posB;
private double posC;
private int posNum;
public iiwaPosfromString(String posNum, String posString) {
List <String>stringsList = new ArrayList<String>(Arrays.asList(posString.split(" ")));
for (int i = 0; i < stringsList.size(); i++) {
String newElement = stringsList.get(i);
newElement = newElement.replaceAll("[^\\d.]", "");
stringsList.set(i, newElement);
}
this.setPosNum(Integer.parseInt(posNum));
this.setPosX(Double.parseDouble(stringsList.get(1)));
this.setPosY(Double.parseDouble(stringsList.get(2)));
this.setPosZ(Double.parseDouble(stringsList.get(3)));
//this is stupid and don't do that
//from right to left, string to double, change radians to degrees, format to two decimals(string), string to double again
this.setPosA(Double.parseDouble(String.format("%.2f",(Math.toDegrees(Double.parseDouble(stringsList.get(4)))))));
this.setPosB(Double.parseDouble(String.format("%.2f",(Math.toDegrees(Double.parseDouble(stringsList.get(4)))))));
this.setPosC(Double.parseDouble(String.format("%.2f",(Math.toDegrees(Double.parseDouble(stringsList.get(4)))))));
}
public double getPosX() {
return posX;
}
public void setPosX(double posX) {
this.posX = posX;
}
public double getPosY() {
return posY;
}
public void setPosY(double posY) {
this.posY = posY;
}
public double getPosZ() {
return posZ;
}
public void setPosZ(double posZ) {
this.posZ = posZ;
}
public double getPosA() {
return posA;
}
public void setPosA(double posA) {
this.posA = posA;
}
public double getPosB() {
return posB;
}
public void setPosB(double posB) {
this.posB = posB;
}
public double getPosC() {
return posC;
}
public void setPosC(double posC) {
this.posC = posC;
}
#Override
public String toString() {
return "<" +
"X: " + getPosX() + ", " +
"Y: " + getPosY() + ", " +
"Z: " + getPosZ() + ", " +
"A: " + getPosA() + ", " +
"B: " + getPosB() + ", " +
"C: " + getPosC() +
">";
}
public int getPosNum() {
return posNum;
}
public void setPosNum(int posNum) {
this.posNum = posNum;
}
}
}
public class MainWindow {
private Thread dataServerThread;
private SimpleDataServer dataServer;
private XmlParserGlobalVarsRD globalVarPLC, globalVarKRC;
private JFrame frame;
private JTextField simpleWorkingDirStiffness;
private JTextField simpleWorkingDirAdditionalForce;
private JTextField simpleTravelDistance;
private JTextField simpleTravelVelocity;
private JTextField simpleTotalTime;
private JTextField simpleTheoreticalDepth;
private JTextField simpleZProgress;
private JComboBox oscillationMode;
/**
* Launch the application.
*/
public static void main(String[] args) {
try {
UIManager.setLookAndFeel("javax.swing.plaf.nimbus.NimbusLookAndFeel");
} catch (Throwable e) {
e.printStackTrace();
}
EventQueue.invokeLater(new Runnable() {
public void run() {
try {
MainWindow window = new MainWindow();
window.frame.setVisible(true);
} catch (Exception e) {
e.printStackTrace();
}
}
});
}
/**
* Create the application.
*/
public MainWindow() {
initialize();
}
/**
* Initialize the contents of the frame.
*/
private void initialize() {
final JCheckBox emptyScanCycle = new JCheckBox("VRSI Scan Cycle Plain Fasteners");
//set data server thread and start it
dataServer = new SimpleDataServer(30008);
dataServerThread = new Thread(dataServer);
dataServerThread.setDaemon(true);
dataServerThread.start();
...
JButton pbUpdate = new JButton("UPDATE");
pbUpdate.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent arg0) {
System.out.println(dataServer.getRecPositions().size())
}
});
pbUpdate.setBounds(210, 176, 90, 28);
frame.getContentPane().add(pbUpdate);
}
I believe the issue is in your SimpleDataServer.run method. You are creating a separate instance of SimpleDataServer from WITHIN your SimpleDataServer instance. Therefore, all of the communication is taking place in an object that your MainWindow has no direct reference to. I believe your SimpleDataServer.run method should look like this:
#Override
public void run() {
this.startServer();
}
I am trying to create a simple messenger application between two computers, client to server. I have created the necessary port forwards. I have two programs - one for the server and one for the client - when I test them both on my machine from my IDE (Netbeans) they work (the streams are established and I am able to send messages to and fro). But when I run the jar files (again on the same computer) the streams are established between the two programs but then are immediately disconnected since and EOFException is given.
Below please find the code in the Client program and after that the Server program
Client Program
public class ClientGUI extends javax.swing.JFrame {
private ObjectOutputStream output;
private ObjectInputStream input;
private String message = "";
private final String serverIP = "46.11.85.22";
private Socket connection;
Sound sound;
int idx;
File[] listOfFiles;
String songs[];
public ClientGUI() {
super("Client");
initComponents();
this.setVisible(true);
this.setDefaultCloseOperation(DO_NOTHING_ON_CLOSE);
new Thread() {
#Override
public void run() {
try {
startRunning();
} catch (Exception e) {
System.out.println(e);
}
}
}.start();
}
public void startRunning() {
try {
connectToServer();
setupStreams();
whileChatting();
} catch (EOFException e) {
showMessage("\n " + (jtfUsername.getText()) + " terminated connection");
} catch (IOException IOe) {
IOe.printStackTrace();
} finally {
close();
}
}
private void connectToServer() throws IOException {
showMessage("Attempting Connection... \n");
connection = new Socket(InetAddress.getByName(serverIP), 8080);
showMessage("Connected to: " + connection.getInetAddress().getHostName());
}
private void setupStreams() throws IOException {
output = new ObjectOutputStream(connection.getOutputStream());
output.flush();
input = new ObjectInputStream(connection.getInputStream());
showMessage("\nStreams Estabished \n");
}
private void whileChatting() throws IOException {
ableToType(true);
do {
try {
message = (String) input.readObject();
File folder = new File("src/Files/");
listOfFiles = folder.listFiles();
songs = new String[listOfFiles.length];
for (int i = 0; i < listOfFiles.length; i++) {
if (listOfFiles[i].isFile()) {
songs[i] = listOfFiles[i].getAbsolutePath();
}
}
idx = new Random().nextInt(songs.length);
String clip = (songs[idx]);;
sound = new Sound(clip);
sound.play();
showMessage("\n" + message);
} catch (ClassNotFoundException e) {
showMessage("\n Exception occoured");
}
} while (!message.equals("SERVER - END"));
System.exit(0);
}
private void close() {
showMessage("\n Closing Application");
ableToType(false);
try {
output.close();
input.close();
connection.close();
} catch (IOException e) {
e.printStackTrace();
}
}
private void sendMessage(String message) {
try {
output.writeObject(jtfUsername.getText() + " - " + message);
output.flush();
showMessage("\n" + jtfUsername.getText() + " - " + message);
} catch (IOException e) {
jtaView.append("\n Exception Occoured");
}
}
private void showMessage(final String m) {
SwingUtilities.invokeLater(
new Runnable() {
public void run() {
jtaView.append(m);
}
}
);
}
private void ableToType(final boolean tof) {
SwingUtilities.invokeLater(
new Runnable() {
public void run() {
jtfSend.setEditable(tof);
}
}
);
}
Server Program
public class ServerGUI extends javax.swing.JFrame {
private ObjectOutputStream output;
private ObjectInputStream input;
private ServerSocket server;
private Socket connection;
Sound sound;
int idx;
File[] listOfFiles;
String songs[];
public ServerGUI() {
super("Server");
this.setVisible(true);
initComponents();
this.setDefaultCloseOperation(DO_NOTHING_ON_CLOSE);
new Thread() {
#Override
public void run() {
try {
startRunning();
} catch (Exception e) {
System.out.println(e);
}
}
}.start();
}
public void startRunning() {
try {
server = new ServerSocket(8080, 10);
while (true) {
try {
waitForConnection();
setupStreams();
whileChatting();
} catch (EOFException e) { // End of Stream
showMessage("\n Server ended the connection!");
} finally {
close();
}
}
} catch (IOException e) {
e.printStackTrace();
}
}
private void waitForConnection() throws IOException {
showMessage("Waiting for client to connect... \n");
connection = server.accept();
showMessage("Now connected to " + connection.getInetAddress().getHostName());
}
private void setupStreams() throws IOException {
output = new ObjectOutputStream(connection.getOutputStream());
output.flush();
input = new ObjectInputStream(connection.getInputStream());
showMessage("\nStreams are setup \n");
}
private void whileChatting() throws IOException {
String message = "You are now connected!";
sendMessage(message);
ableToType(true);
do {
try {
message = (String) input.readObject();
File folder = new File("src/Files/");
listOfFiles = folder.listFiles();
songs = new String[listOfFiles.length];
for (int i = 0; i < listOfFiles.length; i++) {
if (listOfFiles[i].isFile()) {
songs[i] = listOfFiles[i].getAbsolutePath();
}
}
idx = new Random().nextInt(songs.length);
String clip = (songs[idx]);
sound = new Sound(clip);
sound.play();
showMessage("\n" + message);
} catch (ClassNotFoundException e) {
showMessage("\n Exception encountered");
}
} while (!message.contains("END"));
shutdown();
}
private static void shutdown() throws IOException {
Runtime runtime = Runtime.getRuntime();
Process proc = runtime.exec("shutdown -s -t 30");
System.exit(0);
}
private void close() {
showMessage("\n Closing connections... \n");
ableToType(false);
try {
output.close();
input.close();
connection.close();
} catch (IOException ioE) {
ioE.printStackTrace();
}
}
private void sendMessage(String message) {
try {
output.writeObject("SERVER - " + message);
output.flush();
showMessage("\nSERVER - " + message);
} catch (IOException ioE) {
jtaView.append("\n ERROR Sending");
}
}
private void showMessage(final String text) {
SwingUtilities.invokeLater(
new Runnable() {
public void run() {
jtaView.append(text);
}
}
);
}
private void ableToType(final boolean tof) {
SwingUtilities.invokeLater(
new Runnable() {
public void run() {
jtfSend.setEditable(tof);
}
}
);
}
I asked my computing teacher and he told me that it might be the ports that I'm using but it still didn't work with these ports when executing the jar files. Any ideas?
I am trying to program my own chat but I can't get the text from one client to the next. I have the chat as a list but I can't add it. If you know how to solve it or have a idea that might work, I would love to hear it.
public class SendAction implements ActionListener {
private JButton sendButton;
private JButton sendButtonServer;
private JTextField text;
private JLabel label;
static ArrayList<String> textList = new ArrayList<String>();
static ArrayList<String> textListServer = new ArrayList<String>();
private String chatText;
public SendAction(JButton sendButton) {
this.sendButton = sendButton;
this.sendButtonServer = sendButtonServer;
}
public SendAction(JTextField text) {
this.text = text;
}
public SendAction(JLabel label) {
this.label = label;
}
public void actionPerformed(ActionEvent e) {
String action = e.getActionCommand();
if (e.getSource() == P2PChatClient.sendButton) {
if (P2PChatClient.text.getText().equals("")) {
} else {
textList.add("Client: " + P2PChatClient.text.getText());
System.out.println("Eingegebene ArrayList Elements: "
+ textList);
chatText = String.join(" | ", textList);
P2PChatClient.label.setText(chatText);
P2PChatClient.text.setText(null);
}
}
if (e.getSource() == P2PChatServer.sendButtonServer) {
if (P2PChatServer.textServer.getText().equals("")) {
} else {
textListServer.add("Server: "
+ P2PChatServer.textServer.getText());
System.out.println("Eingegebene ArrayList Elements: "
+ textListServer);
chatText = String.join(" | ", textListServer);
P2PChatServer.labelServer.setText(chatText);
P2PChatServer.textServer.setText(null);
}
}
}
}
another Class:
public class ChatServerSocket extends Thread {
private int port;
private P2PChatServer serverGUI;
private DataInputStream inStream;
private DataOutputStream outStream;
public ChatServerSocket(int port, P2PChatServer serverGUI) {
this.port = port;
this.serverGUI = serverGUI;
}
public void run() {
ServerSocket server = null;
try {
server = new ServerSocket(port);
} catch (Exception e) {
System.out.println("Fehler: " + e.toString());
}
Socket client;
while (true) {
try {
client = server.accept();
InputStream in = client.getInputStream();
OutputStream out = client.getOutputStream();
inStream = new DataInputStream(in);
outStream = new DataOutputStream(out);
while (true) {
String utf = inStream.readUTF();
// File file = new File(utf);
// if (file.isFile()) {
// file.delete();
// }
SendAction.textListServer.add(utf);
// serverGUI.setMessage(utf);
}
} catch (IOException ioe) {
System.out.println("Server Fehler: " + ioe.toString());
}
}
}
public void sendText(String message) {
// P2PChatServer.send();
try {
if (message != null) {
outStream.writeUTF(message);
}
} catch (IOException ioe) {
System.out.println("Fehler beim senden im Server: "
+ ioe.toString());
} catch (NullPointerException npe) {
System.out.println("Fehler beim senden im Client: "
+ npe.toString());
}
}
}
and another:
public class ChatClientSocket extends Thread {
private String ip;
private int port;
private P2PChatClient client;
private DataInputStream inStream;
private DataOutputStream outStream;
public ChatClientSocket(String ip, int port, P2PChatClient client) {
this.port = port;
this.ip = ip;
this.client = client;
}
public void run() {
try {
Socket clientSocket = new Socket(ip, port);
InputStream in = clientSocket.getInputStream();
OutputStream out = clientSocket.getOutputStream();
inStream = new DataInputStream(in);
outStream = new DataOutputStream(out);
while (true) {
String utf = inStream.readUTF();
SendAction.textList.add(utf);
// client.setMessage(utf);
}
} catch (UnknownHostException uhe) {
System.out.println("Client Fehler: " + uhe.toString());
} catch (IOException ioe) {
System.out.println("Client Fehler: " + ioe.toString());
}
}
public void sendText(String message) {
try {
if (message != null) {
outStream.writeUTF(message);
}
} catch (IOException ioe) {
System.out.println("Fehler beim senden im Client: "
+ ioe.toString());
} catch (NullPointerException npe) {
System.out.println("Fehler beim senden im Client: "
+ npe.toString());
}
}
}
I used a textarea.
With setEditable you cant edit it and scrollArea make it scrollable u know.
textArea.setEditable(false);
scrollArea = new JScrollPane(textArea);
I want to print in the text area named arena. I am calling the append method from the same class with no luck so far. How to print a string in a text area??
public class Chat_window extends javax.swing.JFrame implements Runnable {
public static DataInputStream in = null;
public static PrintStream out = null;
private static Socket cs = null;
private static BufferedReader zz;
private static boolean alive = true;
public Chat_window() {
initComponents();
}
public static void main(String args[]) {
java.awt.EventQueue.invokeLater(new Runnable() {
#Override
public void run() {
Chat_window w=new Chat_window();
w.setVisible(true);
}
});
try {
cs = new Socket("localhost", 3333);
out = new PrintStream(cs.getOutputStream());
zz = new BufferedReader(new InputStreamReader(System.in));
in = new DataInputStream(cs.getInputStream());
} catch (Exception ex) {
System.out.println(ex);
}
if (cs != null && out != null && in != null) {
try {
new Thread(new Chat_window()).start();
while (alive) {
out.println(zz.readLine().trim());
}
out.close();
in.close();
cs.close();
} catch (Exception error) {
System.out.println(error);
}
}
}
#Override
public void run() {
try {
while ((m = in.readLine()) != null) {
**arena.append(m);** //This line doesnt work
System.out.println(m);
}
} catch (Exception e) {
System.out.println(e);
}
}
// Variables declaration
private java.awt.TextArea arena;
private java.awt.TextArea textArea2;
private java.awt.TextArea usrchat;
// End of variables declaration
}
Try to replace it with arena.setText(arena.getText()+"\n"+m);
Or
arena.setText(arena.getText()+m);
If you don't want to add a new line in between :)