This question already exists:
Scanner issue when using nextLine after nextXXX [duplicate]
Closed 9 years ago.
I am trying to create a java chat and I got this bug: When I use name = scanner.nextLine() my program works apparently fine (but it's not reading any name, if I use System.out.println(name) I get newline), and when I don't use it my pg automaticly connects to server with no name. Can anyone tell me why it;s happening this?
import java.net.*;
import java.util.*;
import java.io.*;
class Cient
{
static String name;
public static void main(String[] args) throws Exception
{
Scanner scanner = new Scanner(System.in);
System.out.print("Adresa serverului si portul : ");//server adress and port
Socket cs = new Socket( scanner.next(), scanner.nextInt() );
DataOutputStream os = new DataOutputStream( cs.getOutputStream());
final DataInputStream is = new DataInputStream( cs.getInputStream());
String st = "";
System.out.println("Va rugam sa va introduceti numele");//get name
name = scanner.nextLine();
Thread T= new Thread(new Runnable()
{
public void run() {
while (true)
{
String s = "";
try
{
s = is.readUTF();
System.out.println(s);
if(s.equals("Intrerupem conexiunea .... Pa!"))//close connexion
{
return;
}
} catch (IOException ex)
{
}
}
}
});
T.start();
while (true)
{
st = scanner.nextLine();
os.writeUTF(st);
if(st.equals("QUIT") || st.equals("EXIT"))
{
return;//stop reading
}
}
}
}
Here is the Server Class, but I dont believe that's important:
import java.io.DataInputStream;
import java.io.DataOutputStream;
import java.io.IOException;
import java.net.ServerSocket;
import java.net.Socket;
import java.util.Scanner;
import java.util.Vector;
public class MyServer
{
Scanner scanner;
Vector<String> users = new Vector<String>();
Vector<HandleClient> clients = new Vector<HandleClient>();
String disconnectedUser = "InvalidUser";//String care imi spune daca un client s-a razgandit la conectare
int PORT;
public Vector<String> getUserList()
{
return users;
}
public void process() throws Exception
{
scanner = new Scanner(System.in);
System.out.println("PORT: ");
PORT = scanner.nextInt();
ServerSocket server = new ServerSocket(PORT);
System.out.println("Server Online...");
while(true)
{
Socket client = server.accept();
HandleClient c = new HandleClient(client);
if(!(c.userName().equals(disconnectedUser)))
{
clients.add(c);
users.add(c.userName());
}
}
}
public static void main(String ... args) throws Exception
{
new MyServer().process();
}
public void broadcast(String user, String message)throws Exception
{
for (HandleClient c : clients)
if (!(c.userName().equals(user)))
{
c.sendMessage(user,message);
}
}
public void twoUsersBroadcast(String fromUser,String toUser, String msg)throws Exception
{
for(HandleClient c : clients)
{
String a = (String) c.userName();
if(a.equals(toUser))
{
c.sendMessage(fromUser,msg);
return ;
}
}
}
public void changeUserName(String actualName,String newName)
{
int i = 0;
for(HandleClient c: clients)
{
if(c.userName().equals(actualName))
{
c.setUserName(newName);
users.set(i,newName);
}
i++;
}
}
boolean validUserName(String name)
{
for(String c : users)
{
if(c.equals(name))
{
return false;
}
}
return true;
}
class HandleClient extends Thread
{
String name = "";
DataInputStream input;
DataOutputStream output;
public String userName()
{
return name;
}
public void setUserName(String name)
{
this.name = name;
}
public void writeError(String message)
{
try
{
output.writeUTF("EROARE: " + message);
}
catch (IOException e)
{
System.out.print(e.getMessage());
}
}
public HandleClient(Socket client)throws Exception
{
input = new DataInputStream(client.getInputStream());
output= new DataOutputStream(client.getOutputStream());
boolean ok = true;
while(ok == true)
{
name = input.readUTF();
if(name.equals("EXIT"))
{
ok = false;
output.writeUTF("Intrerupem conexiunea .... Pa!");
name = "InvalidUser";//User-ul a renuntat la conexiune
}
else
{
if(validUserName(name) == true)
{
ok = false;
}
else
{
output.writeUTF("Numele este deja folosit. Va rugam sa introducet un alt nume sau EXIT in care doriti sa nu va mai conectati");
}
}
}
if("InvalidUser".equals(name))
{
return;
}
start();
}
public void sendMessage(String username,String msg)throws Exception
{
output.writeUTF( username + ": " + msg);
}
public void run()
{
String line;
try
{
boolean ok = true;
output.writeUTF("Introduceti:");
output.writeUTF("LIST pentru a vedea lista de utilizatori");
output.writeUTF("MSG pentru a transmite un mesaj unui anumit utilizator");
output.writeUTF("BCAST pentru a transmite un mesaj tuturor utilizatorilor");
output.writeUTF("NICK pentru a va schimba numele");
output.writeUTF("QUIT pentru a va deconecta de la server");
while(ok == true)
{
line = input.readUTF();
switch(line)
{
case "LIST":
{
Vector<String> users = getUserList();
output.writeUTF("Lista user-ilor este:");
for(String c : users)
{
output.writeUTF(c);
}
break;
}
case "MSG":
{
output.writeUTF("Introduceti numele persoanei careia doriti sa-i trimiteti mesajul");
line = input.readUTF();
if(validUserName(line) == true)
{
writeError("Numele persoanei nu exista");
break;
}
else
{
if(name.equals(line))
{
writeError("Selectati alt user");
break;
}
else
{
output.writeUTF("Introduceti mesajul pe care il aveti de transmis");
String message = input.readUTF();
if((validUserName(line) == false) && !(line.equals(name)))
{
twoUsersBroadcast(name,line,message);
}
break;
}
}
}
case "BCAST":
{
line = input.readUTF();
broadcast(name,line);
break;
}
case "NICK":
{
output.writeUTF("Va rugam sa va introduceti numele dorit");
line = input.readUTF();
if(validUserName(line))
{
changeUserName(name,line);
}
else
{
writeError("Invalid username");
}
break;
}
case "QUIT":
{
output.writeUTF("Intrerupem conexiunea .... Pa!");
clients.remove(this);
users.remove(name);
ok = true;
break;
}
default:
{
writeError("Comanda incorecta");
}
}
}
}
catch(Exception e)
{
System.err.println(e.getMessage());
clients.remove(this);
users.remove(name);
}
}
}
}
After this line:
Socket cs = new Socket( scanner.next(), scanner.nextInt() );
add:
scanner.nextLine();
So together, it would look like:
Socket cs = new Socket( scanner.next(), scanner.nextInt() );
scanner.nextLine();
This is done to swallow the dangling end of line (EOL) token that is not handled by next() or nextInt() and in fact is only handled by nextLine().
Related
I need to implement a program to transfer files. I decided to make it using a chat template I've made about 1 month ago so I would have a chat with file transfer option.
The transfer should follow the following points:
1- Server only keeps a list of all files provided by connected clients (No file are actually located in the server, only their names)
2- Client "1" requests file "A" then:
if file "A" is located ONLY in client "2", then client "2" should send 100% of the file to client "1"
if file "A" is located in client "2" and client "3" also has file "A", then client "2" should send 50% of the file to client "1" and client "3" should send the other 50%.
(if the file is located in 4 clients it should be 25% each....and so it goes...)
I've already managed to make the server find out which client is requesting the file and which clients have it. But now I'm stuck, I don't know how to make the transfer.
Could someone give me an example of how to do it? or point me through the right direction?
[I'm aware my code has some flaws and I will fix it later, right now I need to make the transfer happen before working on fixes, so please, unless it's related, try to focus on that]
Server:
package tor;
import java.util.*;
import java.io.*;
import java.net.*;
public class Server extends Thread {
private String cname;
private Socket client;
public static Vector<PrintStream> clients;
public static Vector<String> clientnames;
public static Vector<String> archives;
public Server(Socket client) {
this.client = client;
}
public static void main(String[] args) {
clients = new Vector<PrintStream>();
clientnames = new Vector<String>();
archives = new Vector<String>();
try {
ServerSocket server = new ServerSocket(2391);
System.out.println("Server Started!!\n");
while (true) {
Socket client = server.accept();
Server s = new Server(client);
s.start();
}
} catch (IOException e) {
System.out.println("Server could not start ");
}
}
#Override
public void run() {
try {
BufferedReader in = new BufferedReader(new InputStreamReader(client.getInputStream()));
PrintStream out = new PrintStream(client.getOutputStream());
cname = in.readLine();
System.out.println(cname + " Connected --- SERVER!");
if (cname == null) {
System.out.println("Unknown Name");
return;
}
clientnames.add(cname);
clients.add(out);
connected(" ********** [", cname, "] Connected! **********");
String arq;
int size = in.read();
System.out.println(size);
for (int i = 0; i < size; i++) {
arq = in.readLine();
archives.add(arq);
}
String msg = in.readLine();
String selected;
while (true) {
while (!(msg).equals("/exit") && !(msg).equals("/Exit") && !(msg).equals("/EXIT")) {
if ((msg).equals("/list") || (msg).equals("/List") || (msg).equals("/list")) {
out.println("-------- Archives List --------");
for (int i = 0; i < archives.size(); i++) {
out.println(i+"- "+archives.get(i));
}
out.println("-------- ******************* --------");
msg = in.readLine();
} else if (msg.equals("/get") || (msg.equals("/GET")) || (msg.equals("/Get"))){
msg = in.readLine();
int gnum = Integer.parseInt(msg);
selected=archives.get(gnum);
returnAll("[", out, "]: ", "idreq");
out.println("1");
reqAll(selected);
// I BELIVE HERE IS THE RIGHT PLACE TO MAKE DE TRANSFER CODE
msg = in.readLine();
} else {
returnAll("[", out, "]: ", msg);
msg = in.readLine();
}
}
msg = in.readLine();
size = Integer.parseInt(msg);
for (int i = 0; i <= size; i++) {
arq = in.readLine();
for(int j=0;j<archives.size();j++) {
if (archives.get(j).equals(arq)) {
archives.remove(j);
}
}
}
returnAll(" ********** [", out, "] disconnected ", " ********** ");
clients.remove(out);
clientnames.remove(cname);
client.close();
break;
}
} catch (IOException e) {
System.out.println("A Client disconnected ");
}
}
// METHOD TO SEND CONNECTION MESSAGE
public void connected(String msg1, String cname, String msg2) throws IOException {
Enumeration<PrintStream> e = clients.elements();
while (e.hasMoreElements()) {
PrintStream message = (PrintStream) e.nextElement();
message.println(msg1 + cname + msg2);
}
}
// METHOD TO RETURN MESSAGE TO ALL CLIENTS
public void returnAll(String msg1, PrintStream saida, String ac, String msg2) throws IOException {
Enumeration<PrintStream> e = clients.elements();
while (e.hasMoreElements()) {
PrintStream message = (PrintStream) e.nextElement();
message.println(msg1 + cname + ac + msg2);
}
}
public void reqAll(String req) throws IOException {
Enumeration<PrintStream> e = clients.elements();
while (e.hasMoreElements()) {
PrintStream message = (PrintStream) e.nextElement();
message.println(req);
}
}
}
Client:
package tor;
import java.io.*;
import java.net.*;
import java.util.ArrayList;
import java.util.Scanner;
public class Client extends Thread {
private Socket con;
private static boolean done = false;
static ArrayList<String> localArq = new ArrayList<String>();
static int c=0;
public Client(Socket s) {
con = s;
}
public static void main(String[] args) {
try {
String ip;
Scanner s = new Scanner(System.in);
System.out.print("Enter Server's IP: ");
ip =s.next();
Socket con = new Socket(ip, 2391);
PrintStream out = new PrintStream(con.getOutputStream());
System.out.println("Connected to Server!");
System.out.print("Enter your Nickname: ");
BufferedReader scan = new BufferedReader(new InputStreamReader(System.in));
String cname = scan.readLine();
out.println(cname);
String dir="C:\\javator\\"+cname;
Thread t = new Client(con);
t.start();
File folder = new File(dir);
folder.mkdir();
File[] listOfFiles = folder.listFiles();
for (int i = 0; i < listOfFiles.length; i++) {
if (listOfFiles[i].isFile()) {
localArq.add(listOfFiles[i].getName());
}
}
int size=localArq.size();
out.write(size);
for(int i=0;i<size;i++) {
out.println(localArq.get(i));
}
String msg;
while (true) {
System.out.print("");
msg = scan.readLine();
if(msg.equals("/ll")) {
System.out.println("-------- LOCAL LIST --------");
for (int i = 0; i < localArq.size(); i++) {
System.out.println(localArq.get(i));
}
System.out.println("-------- ******************* --------");
msg = scan.readLine();
}else if(msg.equals("/exit") || (msg.equals("/Exit")) || (msg.equals("/EXIT"))) {
out.println(msg);
size=localArq.size();
out.println(size);
for(int i=0;i<size;i++) {
out.println(localArq.get(i));
}
}
else if(msg.equals("/get") || (msg.equals("/GET")) || (msg.equals("/Get"))) {
System.out.println("Chose file's number to /get: ");
c++;
}
if (done == true) {
break;
}
out.println(msg);
}
} catch (UnknownHostException e) {
System.out.println(e.getMessage());
} catch (IOException e) {
System.err.println(e.getMessage());
}
}
#Override
public void run() {
try {
BufferedReader in = new BufferedReader(new InputStreamReader(con.getInputStream()));
String rmsg;
String req;
while (true) {
rmsg = in.readLine();
if (rmsg == null) {
System.out.println("Connection Terminated");
break;
}else if(rmsg.substring(rmsg.length() - 5).equals("idreq")) {
req = in.readLine();
for(int i=0;i<localArq.size();i++) { //IDENTIFIES WHO OWNS THE REQUESTED FILE
if(localArq.get(i).equals(req)) {
System.out.println("Owns requested file");
Socket requester = new Socket("192.168.3.114", 2007);
ObjectOutputStream outputr = new ObjectOutputStream(requester.getOutputStream());
ObjectInputStream inputr = new ObjectInputStream(requester.getInputStream());
Object mens= inputr.readObject();
System.out.println(mens);
outputr.writeObject("OWNER FOUND");
}
}
if(c==1) { //IDENTIFIES WHO WANTS THE FILE
rmsg = in.readLine();
c= Integer.parseInt(rmsg);
System.out.println("file: "+req);
ServerSocket peer = new ServerSocket(2007);
System.out.println("OPEN FOR CONNECTIONS\n");
Socket client = peer.accept();
System.out.println("Client connected: " + client.getInetAddress().getHostAddress());
ObjectOutputStream outputo = new ObjectOutputStream(client.getOutputStream());
ObjectInputStream inputo = new ObjectInputStream(client.getInputStream());
outputo.flush();
outputo.writeObject("Connected to requester");
Object mens= inputo.readObject();
System.out.println(mens);
}
}
else {
System.out.println(rmsg);
}
}
} catch (IOException e) {
e.printStackTrace();
} catch (ClassNotFoundException e) {
e.printStackTrace();
}
done = true;
}
}
I was able to make a transfer between two clients easily with the information provided and a little research on stackOverflow to understand more about out/inputStreams!
This post also helped me a lot: Sending a file with Java Sockets, losing data
next step is the shared transfer
I want to use design pattern for this switch - case code.
I tried to use the command pattern, but I could not understand how(I was programming only 2 for months)
I wrote this program to learn how to better program.
My code:
public class Server {
private static final String READ_NEW_MESSAGES = "read new mes";
private static final String SEND_PRIVATE_MESSAGES = "send mes";
private static final String JOIN_CHAT = "find chat";
private static final String CREATE_CHAT = "chating";
private static final String QUIT = "quit";
private static final String EXIT = "exit";
private static final String REGISTRATION = "reg";
private static final String CREATE_PRIVATE_CHAT = "priv chat";
private static final String CONNECT_TO_PRIVATE_CHAT = "connect pm";
private static final String START_CHAT = "Start";
private Populator<PrivateMessage> privateMessagePopulator;
private Populator<Registration> registrationPopulator;
private Populator<Message> messagePopulator;
private Populator<PrivateChat> privateChatPopulator;
private Populator<Chat> publicChatPopulator;
private List<PrivateMessage> privateMessages;
private BufferedReader reader;
private String currentUser;
private Set<String> users;
private static Logger log = Logger.getLogger(Server.class.getName());
private List<Chat> chats;
private String password;
private Set<Registration> registration;
private List<PrivateChat> pmChat;
private String chatName;
public Server() {
server();
}
public void server() {
reader = new BufferedReader(new InputStreamReader(System.in));
privateMessages = new ArrayList<PrivateMessage>();
users = new HashSet<String>();
chats = new ArrayList<Chat>();
privateMessagePopulator = new PrivateMessagePopulator();
privateChatPopulator = new PrivateChatPopulator();
publicChatPopulator = new PublicChatPopulator();
messagePopulator = new MessagePopulator();
registrationPopulator = new RegistratorPopulator();
registration = new HashSet<Registration>();
pmChat = new ArrayList<PrivateChat>();
}
public void start() {
String decition = "";
while (true) {
try {
registrationOrLogin();
} catch (IOException e1) {
e1.printStackTrace();
}
while (decition != QUIT) {
System.out.println("Create a chat - chating");
System.out.println("Join the chat - find chat");
System.out.println("Send private message - send mes");
System.out.println("Read new messages - new mes");
System.out.println("Quit - quit");
System.out.println("Create private chat - priv chat");
System.out.println("Connect to private chat - connect pm");
try {
decition = reader.readLine();
switch (decition) {
case CREATE_PRIVATE_CHAT:
createPrivateChat();
break;
case CREATE_CHAT:
createChat();
break;
case JOIN_CHAT:
joinChat();
break;
case SEND_PRIVATE_MESSAGES:
sendPrivateMessage();
break;
case READ_NEW_MESSAGES:
showNewMessages();
break;
case QUIT:
logout();
break;
case REGISTRATION:
registration();
break;
case CONNECT_TO_PRIVATE_CHAT:
joinToPrivateChat();
break;
default:
break;
}
} catch (IOException e) {
log.warning("Error while reading decition from keyboard. "
+ e.getMessage());
}
}
}
}
private void sendPrivateMessage() throws IOException {
PrivateMessage privateMessage = privateMessagePopulator.populate();
privateMessage.setSenderName(currentUser);
privateMessages.add(privateMessage);
}
private void joinChat() throws IOException {
System.out.println("Exist public chat");
for (Chat chat : chats) {
System.out.println(chat.getChatName());
}
System.out.println("Enter the name of chat you wish to join");
chatName = reader.readLine();
for (Chat chat : chats) {
if (chatName.equals(chat.getChatName())) {
for (Message mes : chat.getMessages()) {
System.out.println(mes.getSenderName() + ": "
+ mes.getContent());
}
publicComunication(chat);
}
}
}
private boolean hasNewMessages() {
boolean result = false;
for (PrivateMessage privateMessage : privateMessages) {
if (currentUser.equals(privateMessage.getReceiverName())) {
result = true;
}
}
for (PrivateChat pm : pmChat) {
if (pm.getAddUserName().equals(currentUser)) {
result = true;
}
}
return result;
}
private void showNewMessages() {
if (hasNewMessages()) {
for (PrivateMessage privateMessage : privateMessages) {
if (currentUser.equals(privateMessage.getReceiverName())
&& MessageStatus.DIDNT_READ.equals(privateMessage
.getStatus())) {
System.out.println(privateMessage.getSenderName() + ": "
+ privateMessage.getContent());
}
privateMessage.setStatus(MessageStatus.ALREADY_READ);
}
}
if (hasNewMessages()) {
for (PrivateChat pm : pmChat) {
for (Message message : pm.getMessages()) {
if (pm.getAddUserName().equals(currentUser)) {
System.out.println(message.getSenderName() + ": "
+ message.getContent());
}
}
}
} else {
System.out.println("you don't have new message ");
}
}
private void registrationOrLogin() throws IOException {
String logOrReg;
System.out
.println("Hi,if you already have account - 1,\nIf you would like to register - 2");
logOrReg = reader.readLine();
if (logOrReg.equals("1")) {
login();
} else if (logOrReg.equals("2")) {
registration();
} else {
registrationOrLogin();
}
}
private boolean hasUser() {
boolean result = false;
for (Registration reg : registration) {
if (currentUser.equals(reg.getUserName())
&& password.equals(reg.getUserPassword())) {
result = true;
}
}
return result;
}
private void login() throws IOException {
System.out.println("Please,enter user name and password ");
currentUser = reader.readLine();
password = reader.readLine();
if (hasUser()) {
System.out.println("You already logged in system");
} else {
System.out.println("Wrong user name or password");
registrationOrLogin();
}
}
private void logout() throws IOException {
currentUser = null;
password = null;
registrationOrLogin();
}
private void createChat() throws IOException {
Chat chat = new Chat();
chat = publicChatPopulator.populate();
publicComunication(chat);
chats.add(chat);
}
private void joinToPrivateChat() throws IOException {
for (PrivateChat pm : pmChat) {
for (String user : pm.getUsers()) {
if (user.equals(currentUser)) {
System.out.println(pm.getChatName());
}
}
}
System.out.println("Enter the name of the chat you wish to join");
chatName = reader.readLine();
for (PrivateChat pm : pmChat) {
if (chatName.equals(pm.getChatName())) {
for (Message message : pm.getMessages()) {
System.out.println(message.getSenderName() + " "
+ message.getContent());
}
privateComunication(pm);
}
}
}
private void createPrivateChat() throws IOException {
PrivateChat privateChat = new PrivateChat();
Set<String> chatUsers = new HashSet<String>();
privateChat = privateChatPopulator.populate();
while (true) {
privateChat.setAddUserName(reader.readLine());
chatUsers.add(privateChat.getAddUserName());
privateChat.setUsers(chatUsers);
for (String user : users) {
if (user.equals(privateChat.getAddUserName())) {
System.out.println("you add too chat user - "
+ privateChat.getAddUserName());
}
}
if (privateChat.getAddUserName().equals(START_CHAT)) {
break;
}
}
privateComunication(privateChat);
pmChat.add(privateChat);
}
private void registration() throws IOException {
Registration reg = registrationPopulator.populate();
registration.add(reg);
currentUser = reg.getUserName();
users.add(reg.getUserName());
}
private void privateComunication(PrivateChat privateChat) {
while (true) {
Message message = messagePopulator.populate();
message.setSenderName(currentUser);
System.out.println(message.getSenderName());
System.out.println("\t" + message.getContent());
if (EXIT.equals(message.getContent())) {
break;
}
privateChat.setStatus(MessageStatus.DIDNT_READ);
privateChat.addMessage(message);
}
}
private void publicComunication(Chat chat) {
while (true) {
Message message = messagePopulator.populate();
message.setSenderName(currentUser);
System.out.println(message.getSenderName());
System.out.println("\t" + message.getContent());
if (EXIT.equals(message.getContent())) {
break;
}
chat.addMessage(message);
}
}
}
I never thought about improving the ugly process of creating shells; never used a switch, but a lot of if-elses, which is the same essentially.
package command.example;
import java.io.BufferedWriter;
import java.io.IOException;
import java.io.OutputStreamWriter;
import java.io.Writer;
import java.util.HashMap;
import java.util.Map;
import java.util.Scanner;
public class CommandExample implements ApplicationContext {
private final Writer writer = new BufferedWriter(new OutputStreamWriter(
System.out));
private boolean quit = false;
private Map<String, Command> commands = new HashMap<>();
{
commands.put("create", new CreateChat(this));
commands.put("join", new JoinChat(this));
commands.put("exit", new ExitCommand(this));
}
public static void main(String[] args) throws Exception {
CommandExample example = new CommandExample();
example.run();
}
public void run() throws IOException {
try (Scanner s = new Scanner(System.in)) {
writer.write("> ");
writer.flush();
while (!quit && s.hasNextLine()) {
String input = s.nextLine().trim();
// get or default is java8, alternatively you could check for null
Command command = commands.getOrDefault(input, new UnknownCommand(this, input));
command.execute();
if (!quit)
writer.write("> ");
writer.flush();
}
}
}
#Override
public void shutdown() {
quit = true;
}
#Override
public Writer getWriter() {
return writer;
}
static interface Command {
public void execute() throws IOException;
}
static abstract class AbstractCommand implements Command {
protected final ApplicationContext context;
protected final Writer writer;
public AbstractCommand(ApplicationContext context) {
this.context = context;
this.writer = context.getWriter();
}
}
static class CreateChat extends AbstractCommand {
public CreateChat(ApplicationContext context) {
super(context);
}
#Override
public void execute() throws IOException {
writer.write(String.format("Successfully created a chat!%n"));
writer.flush();
}
}
static class JoinChat extends AbstractCommand {
public JoinChat(ApplicationContext context) {
super(context);
}
#Override
public void execute() throws IOException {
writer.write(String.format("Successfully joined chat!%n"));
writer.flush();
}
}
static class UnknownCommand extends AbstractCommand {
private final String command;
public UnknownCommand(ApplicationContext context, String command) {
super(context);
this.command = command;
}
#Override
public void execute() throws IOException {
writer.write(String.format("'%s' is not a supported command!%n",
command));
writer.flush();
}
}
static class ExitCommand extends AbstractCommand {
public ExitCommand(ApplicationContext context) {
super(context);
}
#Override
public void execute() throws IOException {
writer.write(String.format("Application is shutting down!%n"));
writer.flush();
context.shutdown();
}
}
};
interface ApplicationContext {
public void shutdown();
public Writer getWriter();
}
Here you have a little start. The Command implementations should not read their input (due to separation of concern), they should specify what they want and some kind of reader should provide it to them (cf. the approach with Writer).
Furthermore I'm asking myself how one would design the QuitProgram command - without using System.exit(0).
I try to make a chat. When a client send a message to the server, it is working, the server receives the message. So I would like to send this message all the clients. I tried many things but they are not working... Just the client which sends the message, it receives this message
Can You help me please ?
Thanks in advance
PS : Sorry for my bad English
This is the result in the console :
http://i.stack.imgur.com/VS2wf.png
MainClient
public class MainClient {
/**
* #param args the command line arguments
* #throws java.io.IOException
* #throws java.lang.ClassNotFoundException
*/
public static void main(String[] args) throws IOException, ClassNotFoundException {
boolean stop = false;
Socket socket;
Scanner nickScan;
String nick;
socket = new Socket(InetAddress.getLocalHost(), 2009);
System.out.println("Hi, what is your name ?");
nickScan = new Scanner(System.in);
nick = nickScan.nextLine();
User u = new User(nick, false, false, true);
ObjectOutputStream oos = new ObjectOutputStream(socket.getOutputStream());
oos.writeObject(u);
EmissionThread e = new EmissionThread(u, socket);
e.start();
while(!stop){
ObjectInputStream ois = new ObjectInputStream(socket.getInputStream());
Message m = (Message)ois.readObject();
System.out.println(m.getNick() + " : " + m.getMsg());
}
//socket.close();//On ferme les connexions
}
}
MainServer
public class MainServer extends Thread {
public static void main(String[] args) throws InterruptedException, IOException {
// TODO code application logic here
ConnectionThread c = new ConnectionThread();
c.start();
}
}
ConnectionThread
public class ConnectionThread extends Thread {
private static final boolean stop = false;
Socket socketduserveur;
ServerSocket socketserver;
Session s = new Session("#upec");
public ConnectionThread() throws IOException {
this.socketserver = new ServerSocket(2009);
}
public ServerSocket getSocketserver() {
return socketserver;
}
#Override
public void run() {
while (!stop) {
try {
socketduserveur = socketserver.accept(); //On accepte les connexions
ObjectInputStream ois = new ObjectInputStream(socketduserveur.getInputStream());
User u = (User)ois.readObject();
System.out.println(u.getNick() + " c'est connecté");
s.addUserList(u);
if (s.listAlone()) {
System.out.println("Vous etes admin");
u.setAdmin(true);
}
ReceptionThread r = new ReceptionThread(socketduserveur);
r.start();
} catch (ClassNotFoundException ex) {
Logger.getLogger(MainServer.class.getName()).log(Level.SEVERE, null, ex);
} catch (IOException ex) {
Logger.getLogger(ConnectionThread.class.getName()).log(Level.SEVERE, null, ex);
}
}
}
}
ReceptionThread
public class ReceptionThread extends Thread {
private static final boolean stop = false;
Socket socketduserveur;
ServerSocket socketserver;
public ReceptionThread(Socket socketduserveur) {
this.socketduserveur = socketduserveur;
}
#Override
public void run() {
while (!stop) {
try {
ObjectInputStream ois = new ObjectInputStream(socketduserveur.getInputStream());
Message m = (Message)ois.readObject();
System.out.println(m.getNick() + " : " + m.getMsg());
ObjectOutputStream oos = new ObjectOutputStream(socketduserveur.getOutputStream());
oos.writeObject(m);
} catch (IOException | ClassNotFoundException ex) {
Logger.getLogger(ReceptionThread.class.getName()).log(Level.SEVERE, null, ex);
}
}
}
}
EmissionThread
public class EmissionThread extends Thread {
private User u;
private Socket socketduserveur;
private static final boolean stop = false;
public EmissionThread(User u, Socket socketduserveur) {
this.u = u;
this.socketduserveur = socketduserveur;
}
#Override
public void run() {
while (!stop) {
try {
Scanner msgScan;
String msg;
msgScan = new Scanner(System.in);
msg = msgScan.nextLine();
Message m = new Message(u.getNick(), msg);
ObjectOutputStream oos = new ObjectOutputStream(socketduserveur.getOutputStream());
oos.writeObject(m);
} catch (IOException ex) {
Logger.getLogger(EmissionThread.class.getName()).log(Level.SEVERE, null, ex);
}
}
}
}
Message
public class Message implements Serializable {
private String nick;
private String msg;
public Message(String nick, String msg) {
this.nick = nick;
this.msg = msg;
}
}
Session
public class Session implements Serializable {
private String name;
private ArrayList<String> listSession = new ArrayList();
private ArrayList<User> listUser = new ArrayList();
public Session(String name) {
this.name = name;
}
public void addSession(String name){
listSession.add(name);
}
public void deleteSession(String name){
for(String s : listSession){
if(name.equals(s)){
listSession.remove(s);
}
}
}
public boolean existSession(String name){
for(String s : listSession){
if(name.equals(s)){
return true;
}
}
return false;
}
public void addUserList(User u){
listUser.add(u);
}
public boolean listAlone(){
int compteur = 0;
for(User u : listUser){
compteur++;
}
return compteur == 1;
}
}
User
public class User implements Serializable {
private String nick;
private final Session session;
private boolean admin, moderator, voice;
public User(String nick, boolean admin, boolean moderator, boolean voice) {
this.nick = nick;
this.admin = admin;
this.moderator = moderator;
this.voice = voice;
this.session = new Session("#upec");
}
}
You can use websockets on tomcat for this. If you download tomcat there is a chat app already built as an example
I am trying to study a multi-client chat server. As i'm new in Java, I am unable to run this two .java files in Net beans. I have two java projects and put I these files under them. Server project runs successfully but client project shows:
Exception in thread "main" java.lang.ArrayIndexOutOfBoundsException: 0
at chatClient.main(chatClient.java:73)
Client Project
import java.net.*;
import java.io.*;
import java.util.*;
import java.awt.*;
class chatClient extends Frame implements Runnable {
Socket soc;
TextField tf;
TextArea ta;
Button btnSend, btnClose;
String sendTo;
String LoginName;
Thread t = null;
DataOutputStream dout;
DataInputStream din;
chatClient(String LoginName, String chatwith) throws Exception {
super(LoginName);
this.LoginName = LoginName;
sendTo = chatwith;
tf = new TextField(50);
ta = new TextArea(50, 50);
btnSend = new Button("Send");
btnClose = new Button("Close");
soc = new Socket("127.0.0.1", 5217);
din = new DataInputStream(soc.getInputStream());
dout = new DataOutputStream(soc.getOutputStream());
dout.writeUTF(LoginName);
t = new Thread(this);
t.start();
}
void setup() {
setSize(600, 400);
setLayout(new GridLayout(2, 1));
add(ta);
Panel p = new Panel();
p.add(tf);
p.add(btnSend);
p.add(btnClose);
add(p);
show();
}
public boolean action(Event e, Object o) {
if (e.arg.equals("Send")) {
try {
dout.writeUTF(sendTo + " " + "DATA" + " " + tf.getText().toString());
ta.append("\n" + LoginName + " Says:" + tf.getText().toString());
tf.setText("");
} catch (Exception ex) {
}
} else if (e.arg.equals("Close")) {
try {
dout.writeUTF(LoginName + " LOGOUT");
System.exit(1);
} catch (Exception ex) {
}
}
return super.action(e, o);
}
public static void main(String args[]) throws Exception {
chatClient Client1 = new chatClient(args[0],args[1]);
Client1.setup();
}
public void run() {
while (true) {
try {
ta.append("\n" + sendTo + " Says :" + din.readUTF());
} catch (Exception ex) {
ex.printStackTrace();
}
}
}
}
Server Project
import java.net.*;
import java.util.*;
import java.io.*;
class chatServer {
static Vector ClientSockets;
static Vector LoginNames;
chatServer() throws Exception {
ServerSocket soc = new ServerSocket(5217);
ClientSockets = new Vector();
LoginNames = new Vector();
while (true) {
Socket CSoc = soc.accept();
AcceptClient obClient = new AcceptClient(CSoc);
}
}
public static void main(String args[]) throws Exception {
chatServer ob = new chatServer();
}
class AcceptClient extends Thread {
Socket ClientSocket;
DataInputStream din;
DataOutputStream dout;
AcceptClient(Socket CSoc) throws Exception {
ClientSocket = CSoc;
din = new DataInputStream(ClientSocket.getInputStream());
dout = new DataOutputStream(ClientSocket.getOutputStream());
String LoginName = din.readUTF();
System.out.println("User Logged In :" + LoginName);
LoginNames.add(LoginName);
ClientSockets.add(ClientSocket);
start();
}
public void run() {
while (true) {
try {
String msgFromClient = new String();
msgFromClient = din.readUTF();
StringTokenizer st = new StringTokenizer(msgFromClient);
String Sendto = st.nextToken();
String MsgType = st.nextToken();
int iCount = 0;
if (MsgType.equals("LOGOUT")) {
for (iCount = 0; iCount < LoginNames.size(); iCount++) {
if (LoginNames.elementAt(iCount).equals(Sendto)) {
LoginNames.removeElementAt(iCount);
ClientSockets.removeElementAt(iCount);
System.out.println("User " + Sendto + " Logged Out ...");
break;
}
}
} else {
String msg = "";
while (st.hasMoreTokens()) {
msg = msg + " " + st.nextToken();
}
for (iCount = 0; iCount < LoginNames.size(); iCount++) {
if (LoginNames.elementAt(iCount).equals(Sendto)) {
Socket tSoc = (Socket) ClientSockets.elementAt(iCount);
DataOutputStream tdout = new DataOutputStream(tSoc.getOutputStream());
tdout.writeUTF(msg);
break;
}
}
if (iCount == LoginNames.size()) {
dout.writeUTF("I am offline");
} else {
}
}
if (MsgType.equals("LOGOUT")) {
break;
}
} catch (Exception ex) {
ex.printStackTrace();
}
}
}
}
}
Thanks in advance.
If you look at your client's constructor you'll see that it requires two arguments:
chatClient(String LoginName, String chatwith)
a login and with whom to chat.
I think you don't specify them so the following line throws an exception because there aren't any and args is empty:
chatClient Client1 = new chatClient(args[0],args[1]);
The java arguments you pass from the command line are actually an array of String. If you do not type anything into the command line (or the NetBeans equivalent you will get an ArrrayIndexOutOfBoundsException. Therefore you get an exception because you try to pass an array of strings into chatClient method without there actually being any arguments.
I'm having issues compiling my code. eclipse gives me this error code:
Exception in thread "main" java.lang.Error: Unresolved compilation problems:
Cannot instantiate the type Module
Cannot instantiate the type Module
at Model.AddModule(Model.java:214)
at Model.loadFromTextFiles(Model.java:129)
at Model.menu(Model.java:98)
at Run.main(Run.java:7)
Here's my model code :
import java.beans.XMLDecoder;
import java.beans.XMLEncoder;
import java.io.*;
import java.util.*;
import com.sun.xml.internal.ws.api.server.Module;
public class Model implements java.io.Serializable {
private Student[] StudentList = new Student[0];
private Module[] ModuleList = new Module[0];
public void runTests() throws FileNotFoundException {
Scanner scan=new Scanner (System.in);
System.out.println("Loading From text files");
scan.nextLine();
loadFromTextFiles();
printReport();
System.out.println("Saving serializable");
scan.nextLine();
saveSer();
System.out.println("Creating a new module(CS12330)");
scan.nextLine();
String[] temp=new String[0];
AddModule("CS12330",temp);
printReport();
System.out.println("Loading from serialixed file");
scan.nextLine();
loadSer();
printReport();
System.out.println("Saving using XML");
scan.nextLine();
saveXML();
System.out.println("Creating a new module(CS15560)");
scan.nextLine();
AddModule("CS15560",temp);
printReport();
System.out.println("Loading from XML file");
scan.nextLine();
loadXML();
printReport();
}
public void menu() throws FileNotFoundException {
while (true) {
System.out.println("Menu");
System.out.println("1-Run Tests");
System.out.println("2-Add Student");
System.out.println("4-Add Module");
System.out.println("5-Add A Student To Module");
System.out.println("6-Save (Text File)");
System.out.println("7-Save (Serialization)");
System.out.println("8-Save (XML)");
System.out.println("9-Load (Text File)");
System.out.println("10-Load (Serialization)");
System.out.println("11-Load (XML)");
Scanner scan=new Scanner (System.in);
String response=scan.nextLine();
if (response.equals("1")){
runTests();
} else if (response.equals("2")) {
System.out.print("Enter UID: ");
String UID=scan.nextLine();
System.out.print("Enter Surname: ");
String surname=scan.nextLine();
System.out.print("Enter First Name: ");
String firstname=scan.nextLine();
System.out.print("Course Code: ");
String courseCode=scan.nextLine();
AddStudent(UID,surname,firstname,courseCode);
} else if (response.equals("4")) {
System.out.print("Enter Module Code: ");
String moduleCode=scan.nextLine();
String[] temp=new String[0];
AddModule(moduleCode,temp);
} else if (response.equals("5")) {
System.out.print("Enter Module Code: ");
String moduleCode=scan.nextLine();
Module m=findAModule(moduleCode);
scan.nextLine();
if(m!=null){
System.out.print("Enter UID: ");
String UID=scan.nextLine();
Student s=findAStudent(UID);
if (s!=null) {
//m.addThisStudent(s);
}else System.out.println("Student Not Found");
}else System.out.println("Module Not Found");
} else if (response.equals("6")) {
saveToTextFiles();
} else if (response.equals("7")) {
saveSer();
} else if (response.equals("8")) {
saveXML();
} else if (response.equals("9")) {
loadFromTextFiles();
} else if (response.equals("10")) {
loadSer();
} else if (response.equals("11")) {
loadXML();
}
}
}
public void loadFromTextFiles() throws FileNotFoundException {
Scanner infile=new Scanner(new InputStreamReader(new FileInputStream("students.txt")));
int num=infile.nextInt();infile.nextLine();
for (int i=0;i<num;i++) {
String u=infile.nextLine();
String sn=infile.nextLine();
String fn=infile.nextLine();
String c=infile.nextLine();
AddStudent(u,sn,fn,c);
}
infile.close();
infile=new Scanner(new InputStreamReader(new FileInputStream("modules.txt")));
num=infile.nextInt();infile.nextLine();
for (int i=0;i<num;i++) {
String c=infile.nextLine();
int numOfStudents=infile.nextInt();infile.nextLine();
String[] students = new String[numOfStudents];
for (int j=0;j<numOfStudents;j++) {
students[j] = infile.nextLine();
}
AddModule(c,students);
}
infile.close();
}
public void saveToTextFiles() {
try {
PrintWriter outfile = new PrintWriter(new OutputStreamWriter (new FileOutputStream("Students.txt")));
outfile.println(StudentList.length);
for(int i=0;i<StudentList.length;i++) {
outfile.println(StudentList[i].getUID());
outfile.println(StudentList[i].getSName());
outfile.println(StudentList[i].getFName());
outfile.println(StudentList[i].getDegree());
}
outfile.close();
outfile = new PrintWriter(new OutputStreamWriter (new FileOutputStream("Modules.txt")));
outfile.println(ModuleList.length);
for(int i=0;i<ModuleList.length;i++) {
outfile.println(ModuleList[i].getCode());
outfile.println(ModuleList[i].getStudents().length);
for (int j=0;j<(ModuleList[i]).getStudents().length;j++) {
outfile.println(ModuleList[i].getStudents()[j]);
}
}
outfile.close();
}
catch(IOException e) {
}
}
public void loadSer() {
Model m =null;
try{
FileInputStream fileIn = new FileInputStream("Model.ser");
ObjectInputStream in = new ObjectInputStream(fileIn);
m=(Model) in.readObject();
in.close();
fileIn.close();
}catch (Exception e){}
if (m!=null) {
setStudentList(m.getStudentList());
setModuleList(m.getModuleList());
}
}
public void saveSer() {
try {
FileOutputStream fileOut = new FileOutputStream("Model.ser");
ObjectOutputStream out = new ObjectOutputStream(fileOut);
out.writeObject(this);
out.close();
fileOut.close();
} catch(IOException e) {}
}
public void loadXML() {
try {
Model m = null;
XMLDecoder decoder = new XMLDecoder (new BufferedInputStream (new FileInputStream("model.xml")));
m = (Model) decoder.readObject();
decoder.close();
setStudentList(m.getStudentList());
setModuleList(m.getModuleList());
} catch (IOException e) {
e.printStackTrace();
}
}
public void saveXML() {
try {
Model m = null;
XMLEncoder encoder = new XMLEncoder (new BufferedOutputStream (new FileOutputStream("model.xml")));
encoder.writeObject(this);
encoder.close();
} catch (IOException e) {
e.printStackTrace();
}
}
private void AddModule(String c, String[] students) {
int length = ModuleList.length;
Module NewArray[]=new Module[length+1];
for (int i=0;i<length+1;i++) {
if (i<length) {
NewArray[i]=new Module(ModuleList[i]);
}
}
NewArray[length]=new Module(c, students);
ModuleList = NewArray.clone();
}
private void AddStudent(String u, String sn, String fn, String c) {
int length = StudentList.length;
Student NewArray[]=new Student[StudentList.length+1];
for (int i=0;i<StudentList.length+1;i++) {
if (i<length) {
NewArray[i]=new Student(StudentList[i]);
}
}
NewArray[length]=new Student(u,sn,fn,c);
StudentList = NewArray.clone();
}
public void printReport() {
for (int i= 0;i<ModuleList.length;i++) {
System.out.println(ModuleList[i].toString(this));
}
}
public Student findAStudent(String UID) {
for(int i=0;i<StudentList.length;i++) {
if (StudentList[i].getUID().compareTo(UID)==0) {
return StudentList[i];
}
}
return null;
}
public Module findAModule(String moduleCode) {
for(int i=0;i<ModuleList.length;i++) {
if (ModuleList[i].getCode().compareTo(moduleCode)==0) {
return ModuleList[i];
}
}
return null;
}
public Module[] getModuleList() {
return ModuleList;
}
public Student[] getStudentList() {
return StudentList;
}
public void setModuleList(Module[] m) {
ModuleList=m.clone();
}
public void setStudentList(Student[] s) {
StudentList=s.clone();
}
}
And here's my module code:
public class Module{
private String Code;
private String[] students = new String[0];
public Module (){};
public Module(String c, String[] s) {
Code=c;
students=s;
}
public Module(Module module) {
Code=module.getCode();
students=module.getStudents();
}
public String[] getStudents() {
return students;
}
public String getCode() {
return Code;
}
public void addThisStudent(Student s) {
AddStudent(s.getUID());
}
public String toString(Model mod) {
String studentString ="";
if (students.length == 0) {
studentString = "\n No Students";
}else {
for (int i=0;i<students.length;i++) {
Student s = mod.findAStudent(students[i]);
if (s!=null) {
studentString += "\n "+s.toString();
}
}
}
return Code + studentString;
}
private void AddStudent(String UIDToAdd) {
int length = students.length;
String NewArray[]=new String[students.length+1];
for (int i=0;i<length;i++) {
NewArray[i] = students[i];
}
NewArray[length] = UIDToAdd;
students = NewArray.clone();
}
}
I honestly have no idea why this is happening. I've googled my error before and I only found issues that involved abstract classes.
You are importing the wrong Module - you are importing:
import com.sun.xml.internal.ws.api.server.Module;
You need to import your own Module.
That's because your imported "com.sun.xml.internal.ws.api.server.Module" in your Model class. Try taking that out and importing your.package.Module instead.