Taking runable class and making it into it's own thread - java

Hey all new to Java some I'm sure this is something simple but just can not get it correctly in order for it to work.
The original java code for this runnable class:
import java.io.IOException;
import java.io.PrintWriter;
import java.net.ServerSocket;
import java.net.Socket;
import java.net.SocketException;
import java.util.HashSet;
import java.util.Scanner;
import java.util.Set;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
public class ChatServer {
private static Set < String > names = new HashSet < > ();
private static Set < PrintWriter > writers = new HashSet < > ();
public static int thePort = 8877;
private static boolean isPortInUse(String host, int port) throws SocketException {
boolean result = false;
try {
(new Socket(host, port)).close();
result = true;
} catch (IOException e) {
// Could not connect.
}
return result;
}
#SuppressWarnings("unused")
public static void main(String[] args) throws Exception {
System.out.println("The chat server is running...");
ExecutorService pool = Executors.newFixedThreadPool(500);
boolean hasPort = isPortInUse("localhost", thePort);
try (ServerSocket listener = new ServerSocket(thePort)) {
while (true) {
pool.execute(new Handler(listener.accept()));
}
}
}
private static class Handler implements Runnable {
private String name;
private Socket socket;
private Scanner in ;
private PrintWriter out;
public Handler(Socket socket) {
this.socket = socket;
}
public void run() {
try {
in = new Scanner(socket.getInputStream());
out = new PrintWriter(socket.getOutputStream(), true);
while (true) {
out.println("SUBMITNAME");
name = in .nextLine();
if (name == null) {
return;
}
synchronized(names) {
if (!name.isEmpty() && !names.contains(name)) {
names.add(name);
break;
}
}
}
out.println("NAMEACCEPTED " + name);
for (PrintWriter writer: writers) {
writer.println("MESSAGE " + name + " has joined");
}
writers.add(out);
while (true) {
String input = in .nextLine();
if (input.toLowerCase().startsWith("/quit")) {
return;
}
for (PrintWriter writer: writers) {
writer.println("MESSAGE " + name + ": " + input);
}
}
} catch (Exception e) {
System.out.println(e);
} finally {
if (out != null) {
writers.remove(out);
}
if (name != null) {
System.out.println(name + " has left");
names.remove(name);
for (PrintWriter writer: writers) {
writer.println("MESSAGE " + name + " has left");
}
}
try {
socket.close();
} catch (IOException e) {}
}
}
}
}
The thread code that I created is this:
static Thread serverThread = new Thread(new Runnable() {
private String name;
private Socket socket;
private Scanner in ;
private PrintWriter out;
#Override
public void run() {
try {
Set < String > names = new HashSet < > ();
Set < PrintWriter > writers = new HashSet < > ();
int thePort = 8877;
System.out.println("The chat server is running...");
ExecutorService pool = Executors.newFixedThreadPool(500);
boolean hasPort = isPortInUse("localhost", thePort);
try (ServerSocket listener = new ServerSocket(thePort)) {
while (true) {
pool.execute(new Handler(listener.accept()));
}
}
try {
in = new Scanner(socket.getInputStream());
out = new PrintWriter(socket.getOutputStream(), true);
while (true) {
out.println("SUBMITNAME");
name = in .nextLine();
if (name == null) {
return;
}
synchronized(names) {
if (!name.isEmpty() && !names.contains(name)) {
names.add(name);
break;
}
}
}
out.println("NAMEACCEPTED " + name);
for (PrintWriter writer: writers) {
writer.println("MESSAGE " + name + " has joined");
}
writers.add(out);
while (true) {
String input = in .nextLine();
if (input.toLowerCase().startsWith("/quit")) {
return;
}
for (PrintWriter writer: writers) {
writer.println("MESSAGE " + name + ": " + input);
}
}
} catch (Exception e) {
System.out.println(e);
} finally {
if (out != null) {
writers.remove(out);
}
if (name != null) {
System.out.println(name + " has left");
names.remove(name);
for (PrintWriter writer: writers) {
writer.println("MESSAGE " + name + " has left");
}
}
try {
socket.close();
} catch (IOException e) {}
}
} catch (Exception e) {
System.out.println(e);
}
}
public void Handler(Socket socket) {
this.socket = socket;
}
private boolean isPortInUse(String host, int port) throws SocketException {
boolean result = false;
try {
(new Socket(host, port)).close();
result = true;
} catch (IOException e) {
// Could not connect.
}
return result;
}
});
The only 2 errors I have out of all of that code above is:
Handler cannot be resolved to a type
on
pool.execute(new Handler(listener.accept()));
and
Return type for the method is missing
on
public Handler(Socket socket) {
So what do I need to change in order to replace Handler so that it will work with the thread code I created?
UPDATE #1
my main class where i call both server and client:
#SuppressWarnings({ "resource", "unused" })
private static void placeChatOnScreen() {
textField = new JTextField();
textField.setFont(new Font("Segoe UI", Font.PLAIN, 13));
textField.setDragEnabled(true);
textField.setBorder(new MatteBorder(1, 1, 1, 1, (Color) new Color(0, 0, 0)));
textField.setBounds(338, 838, 954, 22);
frame.getContentPane().add(textField);
messageArea = new JTextArea();
messageArea.setEditable(false);
messageArea.setFont(new Font("Segoe UI", Font.PLAIN, 13));
messageArea.setBorder(new MatteBorder(1, 1, 1, 1, (Color) new Color(0, 0, 0)));
messageArea.setDragEnabled(true);
messageArea.setName("chatArea");
messageArea.setWrapStyleWord(true);
messageArea.setBounds(338, 648, 954, 181);
frame.getContentPane().add(messageArea);
textField.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
out.println(textField.getText());
textField.setText("");
}
});
// start server
final Thread serverThread = new Thread(new Handler());
serverThread.start();
// wait a bit
Thread.sleep(1000);
// start client
clientThread.start();
}
And this is the server class (as you said to put it in):
public class ChatServer {
private static Set<String> names = new HashSet<>();
private static Set<PrintWriter> writers = new HashSet<>();
public static int thePort = 8877;
private static boolean isPortInUse(String host, int port) throws SocketException {
boolean result = false;
try {
(new Socket(host, port)).close();
result = true;
}
catch(IOException e) {
// Could not connect.
}
return result;
}
#SuppressWarnings("unused")
public static void main(String[] args) throws Exception {
System.out.println("The chat server is running...");
ExecutorService pool = Executors.newFixedThreadPool(500);
boolean hasPort = isPortInUse("localhost", thePort);
try (ServerSocket listener = new ServerSocket(thePort)) {
while (true) {
pool.execute(new Handler(listener.accept()));
}
}
}
public static class Handler implements Runnable {
private String name;
private Socket socket;
private Scanner in;
private PrintWriter out;
public Handler(Socket socket) {
this.socket = socket;
}
public void run() {
try {
in = new Scanner(socket.getInputStream());
out = new PrintWriter(socket.getOutputStream(), true);
while (true) {
out.println("SUBMITNAME");
name = in.nextLine();
if (name == null) {
return;
}
synchronized (names) {
if (!name.isEmpty() && !names.contains(name)) {
names.add(name);
break;
}
}
}
out.println("NAMEACCEPTED " + name);
for (PrintWriter writer : writers) {
writer.println("MESSAGE " + name + " has joined");
}
writers.add(out);
while (true) {
String input = in.nextLine();
if (input.toLowerCase().startsWith("/quit")) {
return;
}
for (PrintWriter writer : writers) {
writer.println("MESSAGE " + name + ": " + input);
}
}
} catch (Exception e) {
System.out.println(e);
} finally {
if (out != null) {
writers.remove(out);
}
if (name != null) {
System.out.println(name + " has left");
names.remove(name);
for (PrintWriter writer : writers) {
writer.println("MESSAGE " + name + " has left");
}
}
try { socket.close(); } catch (IOException e) {}
}
}
}
}
update #2

You declared a private class, which won't be accessible from other classes
private static class Handler implements Runnable { ... }
So, simply mark it as public or package-private (no modifier), if they share the same package
public static class Handler implements Runnable { ... }
Then, do
final Thread serverThread = new Thread(new Handler());
serverThread.start();

Related

Java SocketChannel not receiving incoming data properly

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.

Exception in thread "Thread-0" java.net.BindException: Address already in use: JVM_Bind at

package port_channel;
import java.util.*;
import java.util.concurrent.*;
import java.io.*;
import java.net.*;
public class ChannelPort implements Runnable {
int portNum;
int nSize;
PrintWriter[] outs ;
Listner[] listners;
ConcurrentLinkedQueue<MessageType> que;
public ChannelPort(int portNum, int networkSize) {
this.portNum = portNum;
this.nSize = networkSize;
outs = new PrintWriter[nSize];
listners = new Listner[nSize];
que = new ConcurrentLinkedQueue<MessageType>();
}
public void initialize() {
ServerSocket serverSocket = null;
try {
serverSocket = new ServerSocket(portNum);
} catch (IOException ioe) { }
for (int j = 0; j < nSize; j++) {
try {
Socket clientSocket = serverSocket.accept();
// not part of communication
outs[j] = new PrintWriter(new OutputStreamWriter(clientSocket.getOutputStream()));
ObjectInputStream in = new ObjectInputStream(clientSocket.getInputStream());
listners[j] = new Listner(j, in, this);
} catch (IOException ioe) {
System.err.println("Failed in connection for j=" + j);
ioe.printStackTrace();
System.exit(-1);
}
}
System.out.println("Connections are all established.");
}
//thread
public void run() {
initialize();
for (int j = 0; j < nSize; j++) {
listners[j].start();
}
}
synchronized void gotMessage(MessageType message) {
que.offer(message);
notifyAll();
}
public synchronized MessageType receive() {
while (que.isEmpty()) {
try {
wait();
} catch (InterruptedException ire) {
ire.printStackTrace();
}
}
MessageType msg = que.poll();
System.out.println("receive: " + msg);
return msg;
}
public synchronized void broadcast(String msgStr) {
for (int j = 0; j < outs.length; j++) {
outs[j].println(msgStr);
outs[j].flush();
}
}
public int getPortNum() {
return portNum;
}
public void setPortNum(int portNum) {
this.portNum = portNum;
}
public int getnSize() {
return nSize;
}
public ConcurrentLinkedQueue<MessageType> getQue() {
return que;
}
public static void main(String[] args) throws IOException, InterruptedException {
if (args.length != 2)
System.out.println("usage: java ChannelPort port-number number-of-nodes");
int portNum = Integer.parseInt(args[0]);
int numNode = Integer.parseInt(args[1]);
ChannelPort cp = new ChannelPort(portNum, numNode);
new Thread(cp).start();
Thread.sleep(60000);
System.out.println("Shutdown");
Iterator<MessageType> ite = cp.getQue().iterator();
while (ite.hasNext()) {
System.out.println(ite.next());
}
}
}
//thread
class Listner extends Thread {
int pId;
ObjectInputStream in;
ChannelPort cPort;
boolean done = false;
final int ERR_THRESHOLD = 100;
public Listner(int id, ObjectInputStream in, ChannelPort cPort) {
this.pId = id;
this.in = in;
this.cPort = cPort;
}
public void run() {
MessageType msg;
int errCnt = 0;
while(in != null) {
try {
msg = (MessageType)in.readObject();
System.out.println("process " + pId + ": " + msg);
cPort.gotMessage(msg);
} catch (ClassNotFoundException cnfe) {
cnfe.printStackTrace();
} catch (SocketException se) {
System.err.println(se);
errCnt++;
if (errCnt > ERR_THRESHOLD) System.exit(0);
} catch (IOException ioe) {
ioe.printStackTrace();
}
}
}
}
Did you check the serverSocket created properly ?
You've suppressed the exception while creating the ServerSocket.
catch (IOException ioe) {
//print stack trace and see why exception occurs.
}
serverSocket might be null at 2nd try block, so serverSocket.accept() throws NPE, fix this error

Java How to make server wait for three client responses and send out answers

This is a multi-threaded server client program
The objective is to make the server waits for three responses from clients
and then roll three dices and check the answers accordingly
Currently all I can think of is to use an array list to hold the client responses
and if the length of the list becomes three then check the answers
and send out the results
Running the following codes would not give any errors
but if the client enter a number
it seems that the client answer does not go into the array list correctly
the first client gets result saying that the correct answer is 0
which I guess the game has not started yet so it says 0
the second and third clients get a slew of null returned by the server and disconnected right after I hit enter
so the question is why does it keep returning null for client 2 and client 3?
Server Code:
import java.io.*;
import java.net.*;
import java.util.*;
import java.awt.*;
import javax.swing.*;
public class GameServer extends JFrame {
private JTextArea jta = new JTextArea();
private static int intClient = 0;
public static void main(String[] args) {
new GameServer();
}
public GameServer() {
setLayout(new BorderLayout());
add(new JScrollPane(jta), BorderLayout.CENTER);
setTitle("Game Server");
setSize(500, 300);
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
setVisible(true);
try {
ServerSocket serverSocket = new ServerSocket(8000);
jta.append("Server started at " + new Date() + '\n');
jta.setCaretPosition(jta.getDocument().getLength());
while (true) {
try {
Socket socket = serverSocket.accept();
jta.append("Connected with " + socket.getInetAddress().getHostAddress() + " using socket " + socket.getPort() + '\n');
jta.setCaretPosition(jta.getDocument().getLength());
QuoteServerThread qst = new QuoteServerThread(socket, ++intClient);
qst.start();
}
catch (Exception ex) {
System.err.println(ex);
}
}
}
catch (Exception ex) {
System.err.println(ex);
}
}
private class QuoteServerThread extends Thread {
private Socket socket;
private int intClient;
private BufferedReader inputFromClient;
private PrintWriter outputToClient;
QuoteServerThread(Socket parSocket, int parClient) {
socket = parSocket;
intClient = parClient;
}
public void run() {
if (intClient == 1){
jta.append("Waiting for two more players..." + "\n");
} else if (intClient == 2) {
jta.append("Waiting for one more player..." + "\n");
} else if (intClient == 3) {
jta.append("Game Starts!" + "\n");
jta.append("Waiting for guesses..." + "\n");
}
try {
inputFromClient = new BufferedReader(new InputStreamReader(socket.getInputStream()));
outputToClient = new PrintWriter(new BufferedWriter(new OutputStreamWriter(socket.getOutputStream())));
}
catch (Exception ex) {
System.err.println(ex);
}
while (true) {
try {
SimpleDiceGame game = new SimpleDiceGame();
String str = inputFromClient.readLine();
jta.append("Player"+intClient+" Guess:" + str + "\n");
ArrayList<String> clientGuessList = new ArrayList<String>();
clientGuessList.add(intClient-1,str);
if (clientGuessList.size() == 0){
jta.append("waiting for 3 more answers");
} else if (clientGuessList.size() == 1 ){
jta.append("waiting for 2 more answers");
} else if (clientGuessList.size() == 2 ){
jta.append("waiting for 1 more answer");
} else if (clientGuessList.size() == 3){
game.setDices();
jta.append(game.getDices(1) + " " + game.getDices(2) + " " + game.getDices(3) + "\n");
String result = game.checkAnswer(str,intClient);
outputToClient.println("The result is: " + game.getDices(intClient));
outputToClient.println(result);
outputToClient.flush();
jta.setCaretPosition(jta.getDocument().getLength());
clientGuessList.removeAll(clientGuessList);
}
}
catch (Exception ex) {
try {
inputFromClient.close();
outputToClient.close();
socket.close();
jta.append("Disconnected with Player " + intClient + '\n');
jta.setCaretPosition(jta.getDocument().getLength());
break;
}
catch (Exception ex2) {
System.err.println(ex2);
}
System.err.println(ex);
}
}
intClient--;
jta.append("Number of players: " + intClient + "\n");
}
}
}
Client Code:
import java.io.*;
import java.net.*;
import java.awt.*;
import java.awt.event.*;
import javax.swing.*;
public class GameClient extends JFrame implements Runnable {
private JTextField jtf = new JTextField();
private JTextArea jta = new JTextArea();
private BufferedReader fromServer;
private PrintWriter toServer;
public static void main(String[] args) {
new GameClient();
}
public GameClient() {
JPanel p = new JPanel();
p.setLayout(new BorderLayout());
p.add(new JLabel("Enter quote no."), BorderLayout.WEST);
p.add(jtf, BorderLayout.CENTER);
jtf.setHorizontalAlignment(JTextField.RIGHT);
setLayout(new BorderLayout());
add(p, BorderLayout.NORTH);
add(new JScrollPane(jta), BorderLayout.CENTER);
jtf.addActionListener(new ButtonListener());
setTitle("Quote Client");
setSize(500, 300);
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
setVisible(true);
Thread th = new Thread(this);
th.start();
}
public void run() {
try {
Socket socket = new Socket("localhost", 8000);
fromServer = new BufferedReader(new InputStreamReader(socket.getInputStream()));
toServer = new PrintWriter(new BufferedWriter(new OutputStreamWriter(socket.getOutputStream())));
while (true) {
try {
String str = fromServer.readLine();
jta.append(str + '\n');
jta.setCaretPosition(jta.getDocument().getLength());
}
catch (Exception ex) {
fromServer.close();
toServer.close();
socket.close();
System.err.println(ex);
}
}
}
catch (Exception ex) {
System.err.println(ex);
}
}
private class ButtonListener implements ActionListener {
public void actionPerformed(ActionEvent e) {
try {
String str = jtf.getText().trim();
jtf.setSelectionStart(0);
jtf.setSelectionEnd(jtf.getDocument().getLength());
toServer.println(str);
toServer.flush();
jta.append("Your guess is: " + str + "\n");
jta.setCaretPosition(jta.getDocument().getLength());
}
catch (Exception ex) {
System.err.println(ex);
}
}
}
}
SimpleDiceGame:
import java.util.Random;
public class SimpleDiceGame {
int[] rolledDices = new int[3];
public String checkAnswer(String stringGuess, int playernum){
int intGuess = 0;
intGuess = Integer.parseInt(stringGuess);
String testResult = null;
if (intGuess == rolledDices[playernum-1]) {
testResult = "Congratulation! You have won!";
} else {
testResult = "Sorry, you missed";
}
return testResult;
}
public void setDices(){
Random r = new Random();
int a = 1+r.nextInt(6);
int b = 1+r.nextInt(6);
int c = 1+r.nextInt(6);
rolledDices[0] = a;
rolledDices[1] = b;
rolledDices[2] = c;
}
public int getDices(int playernum){
return rolledDices[playernum-1];
}
}
I can see at least two things that could cause problems:
ArrayList<String> clientGuessList = new ArrayList<String>(); -
This line should be outside the while(true) else it will be created
anew for each iteration.
The ArrayIndexOutOfBoundsException might be
caused due to clientGuessList.add(intClient-1,str);. Do you
really need to insert into a specific place in the ArrayList? try
using just clientGuessList.add(str);

program to show a progress bar while transferring all files from one server to another in java

i have written a java code to transfer files from one server to another using the concept of socket programming. now in the same code i also want to check for the network connection availability before each file is transferred. i also want that the files transferred should be transferred according to their numerical sequence. And while the files are being transferred the transfer progress of each file i.e the progress percentage bar should also be visible on the screen.
i will really appreciate if someone can help me with the code. i am posting the code i have written for file transfer.
ClientMain.java
import java.io.*;
import java.net.Socket;
import java.net.SocketException;
import java.nio.ByteBuffer;
import java.nio.channels.FileChannel;
public class ClientMain {
private DirectoryTxr transmitter = null;
Socket clientSocket = null;
private boolean connectedStatus = false;
private String ipAddress;
String srcPath = null;
String dstPath = "";
public ClientMain() {
}
public void setIpAddress(String ip) {
this.ipAddress = ip;
}
public void setSrcPath(String path) {
this.srcPath = path;
}
public void setDstPath(String path) {
this.dstPath = path;
}
private void createConnection() {
Runnable connectRunnable = new Runnable() {
public void run() {
while (!connectedStatus) {
try {
clientSocket = new Socket(ipAddress, 3339);
connectedStatus = true;
transmitter = new DirectoryTxr(clientSocket, srcPath, dstPath);
} catch (IOException io) {
io.printStackTrace();
}
}
}
};
Thread connectionThread = new Thread(connectRunnable);
connectionThread.start();
}
public static void main(String[] args) {
ClientMain main = new ClientMain();
main.setIpAddress("10.6.3.92");
main.setSrcPath("E:/temp/movies/");
main.setDstPath("D:/tcp/movies");
main.createConnection();
}
}
(DirectoryTxr.java)
import java.io.*;
import java.net.Socket;
import java.net.SocketException;
import java.nio.ByteBuffer;
import java.nio.channels.FileChannel;
public class DirectoryTxr {
Socket clientSocket = null;
String srcDir = null;
String dstDir = null;
byte[] readBuffer = new byte[1024];
private InputStream inStream = null;
private OutputStream outStream = null;
int state = 0;
final int permissionReqState = 1;
final int initialState = 0;
final int dirHeaderSendState = 2;
final int fileHeaderSendState = 3;
final int fileSendState = 4;
final int fileFinishedState = 5;
private boolean isLive = false;
private int numFiles = 0;
private int filePointer = 0;
String request = "May I send?";
String respServer = "Yes,You can";
String dirResponse = "Directory created...Please send files";
String fileHeaderRecvd = "File header received ...Send File";
String fileReceived = "File Received";
String dirFailedResponse = "Failed";
File[] opFileList = null;
public DirectoryTxr(Socket clientSocket, String srcDir, String dstDir) {
try {
this.clientSocket = clientSocket;
inStream = clientSocket.getInputStream();
outStream = clientSocket.getOutputStream();
isLive = true;
this.srcDir = srcDir;
this.dstDir = dstDir;
state = initialState;
readResponse(); //starting read thread
sendMessage(request);
state = permissionReqState;
} catch (IOException io) {
io.printStackTrace();
}
}
private void sendMessage(String message) {
try {
sendBytes(request.getBytes("UTF-8"));
} catch (UnsupportedEncodingException e) {
e.printStackTrace();
}
}
/**
* Thread to read response from server
*/
private void readResponse() {
Runnable readRunnable = new Runnable() {
public void run() {
while (isLive) {
try {
int num = inStream.read(readBuffer);
if (num > 0) {
byte[] tempArray = new byte[num];
System.arraycopy(readBuffer, 0, tempArray, 0, num);
processBytes(tempArray);
}
} catch (SocketException se) {
System.exit(0);
} catch (IOException io) {
io.printStackTrace();
isLive = false;
}
}
}
};
Thread readThread = new Thread(readRunnable);
readThread.start();
}
private void sendDirectoryHeader() {
File file = new File(srcDir);
if (file.isDirectory()) {
try {
String[] childFiles = file.list();
numFiles = childFiles.length;
String dirHeader = "$" + dstDir + "#" + numFiles + "&";
sendBytes(dirHeader.getBytes("UTF-8"));
} catch (UnsupportedEncodingException en) {
en.printStackTrace();
}
} else {
System.out.println(srcDir + " is not a valid directory");
}
}
private void sendFile(String dirName) {
File file = new File(dirName);
if (!file.isDirectory()) {
try {
int len = (int) file.length();
int buffSize = len / 8;
//to avoid the heap limitation
RandomAccessFile raf = new RandomAccessFile(file, "rw");
FileChannel channel = raf.getChannel();
int numRead = 0;
while (numRead >= 0) {
ByteBuffer buf = ByteBuffer.allocate(1024 * 100000);
numRead = channel.read(buf);
if (numRead > 0) {
byte[] array = new byte[numRead];
System.arraycopy(buf.array(), 0, array, 0, numRead);
sendBytes(array);
}
}
System.out.println("Finished");
} catch (IOException io) {
io.printStackTrace();
}
}
}
private void sendHeader(String fileName) {
try {
File file = new File(fileName);
if (file.isDirectory())
return;//avoiding child directories to avoid confusion
//if want we can sent them recursively
//with proper state transitions
String header = "&" + fileName + "#" + file.length() + "*";
sendHeader(header);
sendBytes(header.getBytes("UTF-8"));
} catch (UnsupportedEncodingException e) {
e.printStackTrace();
}
}
private void sendBytes(byte[] dataBytes) {
synchronized (clientSocket) {
if (outStream != null) {
try {
outStream.write(dataBytes);
outStream.flush();
} catch (IOException io) {
io.printStackTrace();
}
}
}
}
private void processBytes(byte[] data) {
try {
String parsedMessage = new String(data, "UTF-8");
System.out.println(parsedMessage);
setResponse(parsedMessage);
} catch (UnsupportedEncodingException u) {
u.printStackTrace();
}
}
private void setResponse(String message) {
if (message.trim().equalsIgnoreCase(respServer) && state == permissionReqState) {
state = dirHeaderSendState;
sendDirectoryHeader();
} else if (message.trim().equalsIgnoreCase(dirResponse) && state == dirHeaderSendState) {
state = fileHeaderSendState;
if (LocateDirectory()) {
createAndSendHeader();
} else {
System.out.println("Vacant or invalid directory");
}
} else if (message.trim().equalsIgnoreCase(fileHeaderRecvd) && state == fileHeaderSendState) {
state = fileSendState;
sendFile(opFileList[filePointer].toString());
state = fileFinishedState;
filePointer++;
} else if (message.trim().equalsIgnoreCase(fileReceived) && state == fileFinishedState) {
if (filePointer < numFiles) {
createAndSendHeader();
}
System.out.println("Successfully sent");
} else if (message.trim().equalsIgnoreCase(dirFailedResponse)) {
System.out.println("Going to exit....Error ");
// System.exit(0);
} else if (message.trim().equalsIgnoreCase("Thanks")) {
System.out.println("All files were copied");
}
}
private void closeSocket() {
try {
clientSocket.close();
} catch (IOException e) {
e.printStackTrace();
}
}
private boolean LocateDirectory() {
boolean status = false;
File file = new File(srcDir);
if (file.isDirectory()) {
opFileList = file.listFiles();
numFiles = opFileList.length;
if (numFiles <= 0) {
System.out.println("No files found");
} else {
status = true;
}
}
return status;
}
private void createAndSendHeader() {
File opFile = opFileList[filePointer];
String header = "&" + opFile.getName() + "#" + opFile.length() + "*";
try {
state = fileHeaderSendState;
sendBytes(header.getBytes("UTF-8"));
} catch (UnsupportedEncodingException e) {
}
}
private void sendListFiles() {
createAndSendHeader();
}
}
(ServerMain.java)
public class ServerMain {
public ServerMain() {
}
public static void main(String[] args) {
DirectoryRcr dirRcr = new DirectoryRcr();
}
}
(DirectoryRcr.java)
import java.io.*;
import java.net.ServerSocket;
import java.net.Socket;
import java.net.SocketException;
public class DirectoryRcr {
String request = "May I send?";
String respServer = "Yes,You can";
String dirResponse = "Directory created...Please send files";
String dirFailedResponse = "Failed";
String fileHeaderRecvd = "File header received ...Send File";
String fileReceived = "File Received";
Socket socket = null;
OutputStream ioStream = null;
InputStream inStream = null;
boolean isLive = false;
int state = 0;
final int initialState = 0;
final int dirHeaderWait = 1;
final int dirWaitState = 2;
final int fileHeaderWaitState = 3;
final int fileContentWaitState = 4;
final int fileReceiveState = 5;
final int fileReceivedState = 6;
final int finalState = 7;
byte[] readBuffer = new byte[1024 * 100000];
long fileSize = 0;
String dir = "";
FileOutputStream foStream = null;
int fileCount = 0;
File dstFile = null;
public DirectoryRcr() {
acceptConnection();
}
private void acceptConnection() {
try {
ServerSocket server = new ServerSocket(3339);
socket = server.accept();
isLive = true;
ioStream = socket.getOutputStream();
inStream = socket.getInputStream();
state = initialState;
startReadThread();
} catch (IOException io) {
io.printStackTrace();
}
}
private void startReadThread() {
Thread readRunnable = new Thread() {
public void run() {
while (isLive) {
try {
int num = inStream.read(readBuffer);
if (num > 0) {
byte[] tempArray = new byte[num];
System.arraycopy(readBuffer, 0, tempArray, 0, num);
processBytes(tempArray);
}
sleep(100);
} catch (SocketException s) {
} catch (IOException e) {
e.printStackTrace();
} catch (InterruptedException i) {
i.printStackTrace();
}
}
}
};
Thread readThread = new Thread(readRunnable);
readThread.start();
}
private void processBytes(byte[] buff) throws InterruptedException {
if (state == fileReceiveState || state == fileContentWaitState) {
//write to file
if (state == fileContentWaitState)
state = fileReceiveState;
fileSize = fileSize - buff.length;
writeToFile(buff);
if (fileSize == 0) {
state = fileReceivedState;
try {
foStream.close();
} catch (IOException io) {
io.printStackTrace();
}
System.out.println("Received " + dstFile.getName());
sendResponse(fileReceived);
fileCount--;
if (fileCount != 0) {
state = fileHeaderWaitState;
} else {
System.out.println("Finished");
state = finalState;
sendResponse("Thanks");
Thread.sleep(2000);
System.exit(0);
}
System.out.println("Received");
}
} else {
parseToUTF(buff);
}
}
private void parseToUTF(byte[] data) {
try {
String parsedMessage = new String(data, "UTF-8");
System.out.println(parsedMessage);
setResponse(parsedMessage);
} catch (UnsupportedEncodingException u) {
u.printStackTrace();
}
}
private void setResponse(String message) {
if (message.trim().equalsIgnoreCase(request) && state == initialState) {
sendResponse(respServer);
state = dirHeaderWait;
} else if (state == dirHeaderWait) {
if (createDirectory(message)) {
sendResponse(dirResponse);
state = fileHeaderWaitState;
} else {
sendResponse(dirFailedResponse);
System.out.println("Error occurred...Going to exit");
System.exit(0);
}
} else if (state == fileHeaderWaitState) {
createFile(message);
state = fileContentWaitState;
sendResponse(fileHeaderRecvd);
} else if (message.trim().equalsIgnoreCase(dirFailedResponse)) {
System.out.println("Error occurred ....");
System.exit(0);
}
}
private void sendResponse(String resp) {
try {
sendBytes(resp.getBytes("UTF-8"));
} catch (UnsupportedEncodingException e) {
e.printStackTrace();
}
}
private boolean createDirectory(String dirName) {
boolean status = false;
dir = dirName.substring(dirName.indexOf("$") + 1, dirName.indexOf("#"));
fileCount = Integer.parseInt(dirName.substring(dirName.indexOf("#") + 1, dirName.indexOf("&")));
if (new File(dir).mkdir()) {
status = true;
System.out.println("Successfully created directory " + dirName);
} else if (new File(dir).mkdirs()) {
status = true;
System.out.println("Directories were created " + dirName);
} else if (new File(dir).exists()) {
status = true;
System.out.println("Directory exists" + dirName);
} else {
System.out.println("Could not create directory " + dirName);
status = false;
}
return status;
}
private void createFile(String fileName) {
String file = fileName.substring(fileName.indexOf("&") + 1, fileName.indexOf("#"));
String lengthFile = fileName.substring(fileName.indexOf("#") + 1, fileName.indexOf("*"));
fileSize = Integer.parseInt(lengthFile);
dstFile = new File(dir + "/" + file);
try {
foStream = new FileOutputStream(dstFile);
System.out.println("Starting to receive " + dstFile.getName());
} catch (FileNotFoundException fn) {
fn.printStackTrace();
}
}
private void writeToFile(byte[] buff) {
try {
foStream.write(buff);
} catch (IOException io) {
io.printStackTrace();
}
}
private void sendBytes(byte[] dataBytes) {
synchronized (socket) {
if (ioStream != null) {
try {
ioStream.write(dataBytes);
} catch (IOException io) {
io.printStackTrace();
}
}
}
}
}
ClientMain.java and DirectoryTxr.java are the two classes under client application. ServerMain.java and DirectoryRcr.java are the two classes under Server application.
run the ClientMain.java and ServerMain.java
You can sort an array using Arrays.sort(...)
ie
String[] childFiles = file.list();
Arrays.sort(childFiles);
As I understand it, this will sort the files in natural order, based on the file name.
You can modify this by passing a custom Comparator...
Arrays.sort(childFiles, new Comparator<File>() {...}); // Fill out with your requirements...
Progress monitoring will come down to your requirements. Do you want to see only the overall progress of the number of files, the individual files, a combination of both?
What I've done in the past is pre-iterated the file list, calculated the total number of bytes to be copied and used a ProgressMonitor to display the overall bytes been copied...
Otherwise you will need to supply your own dialog. In either case, you will need use SwingUtilities.invokeLater to update them correctly.
Check out Concurrency in Swing for more details.
Network connectivity is subjective. You could simply send a special "message" to there server and wait for a response, but this only suggests that the message was sent and a recipt was received. It could just as easily fail when you start transfering the file again...

Swing problem!(problem in showing a frame)

sorry for posting a lot of code!!I don't know that why my ListFrame doesn't work???
these are the classes.At first I run the MainServer and then I will run the MainFrame in the other package.and then by inserting a correct user name and password ,the Listframe will be shown,BUT I click on menu bar or list or delete button but nothing will happen.why?? please help me.
MainSerevr class :
public class MainServer {
static Socket client = null;
static ServerSocket server = null;
public static void main(String[] args) {
System.out.println("Server is starting...");
System.out.println("Server is listening...");
try {
server = new ServerSocket(5050);
} catch (IOException ex) {
System.out.println("Could not listen on port 5050");
System.exit(-1);
}
try {
client = server.accept();
System.out.println("Client Connected...");
} catch (IOException e) {
System.out.println("Accept failed: 5050");
System.exit(-1);
}
try {
BufferedReader streamIn = new BufferedReader(new InputStreamReader(client.getInputStream()));
boolean done = false;
String line;
while (!done) {
line = streamIn.readLine();
if (line.equalsIgnoreCase(".bye")) {
done = true;
} else {
System.out.println("Client says: " + line);
}
}
streamIn.close();
client.close();
server.close();
} catch (IOException e) {
System.out.println("IO Error in streams " + e);
}
}}
ListFrame:
public class ListFrame extends javax.swing.JFrame implements PersonsModelChangeListener {
private InformationClass client;
private static DefaultListModel model = new DefaultListModel();
private ListSelectionModel moDel;
/** Creates new form ListFrame */
public ListFrame(InformationClass client) {
initComponents();
this.client = client;
jList1.setSelectionMode(ListSelectionModel.SINGLE_SELECTION);
fillTable();
Manager.addListener(this);
}
private void deleteAPerson() {
int index = jList1.getSelectedIndex();
String yahooId = (String) jList1.getSelectedValue();
model.remove(index);
Manager.removeApersonFromSQL(yahooId);
int size = model.getSize();
if (size == 0) {
jButton1.setEnabled(false);
} else {
if (index == size) {
index--;
}
jList1.setSelectedIndex(index);
jList1.ensureIndexIsVisible(index);
}
}
private void jMenuItem2ActionPerformed(java.awt.event.ActionEvent evt) {
AddAPerson frame = new AddAPerson(client);
frame.setVisible(true);
}
private void jButton1ActionPerformed(java.awt.event.ActionEvent evt) {
deleteAPerson();
}
private void jList1ValueChanged(javax.swing.event.ListSelectionEvent evt) {
MainClient.setText("");
MainClient.runAClient();
ChatFrame frame = new ChatFrame(client);
frame.setVisible(true);
}
public void fillTable() {
try {
List<InformationClass> list = null;
list = Manager.getClientListFromMySQL();
if (list == null) {
JOptionPane.showMessageDialog(this, "You should add a person to your list", "Information", JOptionPane.OK_OPTION);
return;
} else {
for (int i = 0; i < list.size(); i++) {
InformationClass list1 = list.get(i);
model.add(i, list1.getId());
}
jList1.setModel(model);
}
} catch (SQLException ex) {
Logger.getLogger(ListFrame.class.getName()).log(Level.SEVERE, null, ex);
}
}
MainClient class:
public class MainClient {
private static InformationClass info = new InformationClass();
private static Socket c;
private static String text;
public static String getText() {
return text;
}
public static void setText(String text) {
MainClient.text = text;
}
private static PrintWriter os;
private static BufferedReader is;
static boolean closed = false;
/**
* #param args the command line arguments
*/
public static void runAClient() {
try {
c = new Socket("localhost", 5050);
os = new PrintWriter(c.getOutputStream());
is = new BufferedReader(new InputStreamReader(c.getInputStream()));
String teXt = getText();
os.println(teXt);
if(c!=null&& is!=null&&os!=null){
String line = is.readLine();
System.out.println("Text received: " + line);
}
c.close();
is.close();
os.close();
} catch (UnknownHostException ex) {
System.err.println("Don't know about host");
} catch (Exception e) {
System.err.println("IOException: " + e);
}
}
}
EDIT:I have found the problem,which is because of writting MainClient.runAClient() in code ,where should I put it? please help me.
This article contains an sscce that illustrates a simple client-server GUI. You may find it instructive. If so, consider how you would address the bug found in the last line of the Echo(Kind kind) constructor.

Categories