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
Related
I have a Client class and a MessageServer class that communicates to each other via Sockets. And they send Message object to each other(Not implemented yet).
The thing is, in my MesageServer class, i have a implementation like this
LinkedList<Client> clients = new LinkedList<>();
LinkedList<ObjectOutputStream> outs = new LinkedList<>();
LinkedList<ObjectInputStream> ins = new LinkedList<>();
But this approach seems odd and not useful the more i think about it.
I want to get Message objects from 1 output stream, because that way, I don't have to iterate through every OOS object to find out which client actually put an object in the stream.
Am I wrong? How should I approach?
MessageServer
public class MessageServer extends Server implements Runnable{
static LinkedList<Message> messages = new LinkedList<>();
LinkedList<Client> clients = new LinkedList<>();
LinkedList<ObjectOutputStream> outs = new LinkedList<>();
LinkedList<ObjectInputStream> ins = new LinkedList<>();
ExecutorService threads = Executors.newFixedThreadPool(3);
ExecutorService clientThreads = Executors.newCachedThreadPool();
public MessageServer() throws IOException {
super(Vars.MESSAGE_PORT);
}
//Accept the connetions to the server
private class ServerConnection implements Runnable{
#Override
public void run(){
while (true) {
try {
Socket client = serverSocket.accept();
//Read Client data then add to the list
ObjectOutputStream out = new ObjectOutputStream(client.getOutputStream());
ObjectInputStream in = new ObjectInputStream(client.getInputStream());
outs.add(out);
ins.add(in);
Client current = (Client) in.readObject();
if(current.getType()) {
Provider p = (Provider) current;
clients.add(p);
}else{
Receiver r = (Receiver) current;
clients.add(r);
}
} catch (IOException | ClassNotFoundException ex) {
Logger.getLogger(MessageServer.class.getName()).log(Level.SEVERE, null, ex);
}
}
}
}
private class ServerIO implements Runnable{
#Override
public void run(){
}
}
public void addToMessages(Message message) {
if (!messages.contains(message)) {
messages.add(message);
}
}
#Override
public void run() {
threads.execute(new ServerConnection());
threads.execute(new ServerIO());
}
}
The Provider and Receiver classes are subclasses of the class Client, they are there for future video stream and act the same way for now.
Message
public class Message implements Serializable {
private final int maxChar = 250;
private String content;
private String timeStamp;
private Client sender;
public Message(Client sender, String content, String timeStamp) {
this.sender = sender;
this.content = content;
this.timeStamp = timeStamp;
}
}
Client
public class Client implements Serializable {
protected String nickname;
protected long id;
protected int key;
/*
* True -> Provider
* False -> Receiver
*/
protected boolean type;
// MessageServer
protected transient ObjectOutputStream msgOut;
protected transient ObjectInputStream msgIn;
protected transient Socket messageSocket;
protected transient Socket videoSocket;
public Client(String nickname, boolean type){
this.type = type;
this.nickname = nickname;
createid();
makeConnection();
key = (int) (Math.random() * 8999) + 1000;
}
void makeConnection(){
try {
messageSocket = new Socket(Vars.IP, Vars.MESSAGE_PORT);
//TODO make connection with videoServer
msgOut = new ObjectOutputStream(messageSocket.getOutputStream());
msgIn = new ObjectInputStream(messageSocket.getInputStream());
msgOut.writeObject(this);
} catch (IOException ex) {
Logger.getLogger(Client.class.getName()).log(Level.SEVERE, null, ex);
}
}
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 am working on a project where I send supposedly press a button on a webpage and it then executes a command in java. What I'm looking for is something like this. Say if I pressed a button and then it sends a command to the minecraft server to reload plugins. How would I go achieving this? Thanks
When you have to comunicate between different applications you will problably need a bridge. In your case I'd suggest to use Minecraft's RCON service (must be enabled in the confingiration) or a plugin that do something similar, like Websend.
Websend code is actually available on Github if you would like to know how the plugin work.
Connection between PHP and Java through sockets
Step 1:
Create a java server
I have created a nice API for these situations. you can use them if you would like:
ChatServer
all you need to do is create a new instance of this class
package com.weebly.foxgenesis.src;
import java.net.*;
import java.util.ArrayList;
import java.util.List;
import java.util.StringTokenizer;
import java.io.*;
public final class ChatServer implements Runnable
{
private final int CLIENTMAXIMUM;
private ChatServerThread clients[];
private ServerSocket server = null;
private Thread thread = null;
private int clientCount = 0;
private final ServerReciever output;
private List<ConnectHandler> connectHandlers = new ArrayList<ConnectHandler>();
private List<QuitHandler> quitHandlers = new ArrayList<QuitHandler>();
/**
* creates a new ChatServer for connection between clients
* #param a ServerReciever implementing class
*/
public ChatServer(ServerReciever a)
{
CLIENTMAXIMUM = a.getMaximunClients();
output = a;
clients = new ChatServerThread[CLIENTMAXIMUM];
try
{
server = new ServerSocket();
server.bind(new InetSocketAddress(output.getHost(), output.getPort()));
log(server);
start();
}
catch(IOException ioe)
{
error("Can not bind to port " + a.getPort() + ": " + ioe.getMessage());
}
}
/**
* Force the Server to handle a msg
*/
public void add(String text)
{
output.handle(text);
}
/**
* Force the Server to handle an error
*/
public void error(String text)
{
output.handleError(text);
}
/**
* Log to the server
*/
public void log(Object text)
{
output.handleLog(text);
}
/**
* send a message to a specific client
* #param ID ID of client
* #param msg
*/
public void send(int ID, String msg)
{
clients[findClient(ID)].send(msg);
add(msg);
}
/**
* Called by runnable
*/
public void run()
{
while (thread != null)
{
try
{
if(clientCount != CLIENTMAXIMUM){
log("Waiting for a client ...");
addThread(server.accept());
}
}
catch(IOException ioe)
{
error("Server accept error: " + ioe);
stop();
}
}
}
private void start()
{
if (thread == null)
{
thread = new Thread(this);
thread.start();
}
}
/**
* Stops the server
*/
#SuppressWarnings("deprecation")
public void stop()
{
if (thread != null)
{
thread.stop();
thread = null;
}
}
private int findClient(int ID)
{
for (int i = 0; i < clientCount; i++)
if (clients[i].getID() == ID)
return i;
return -1;
}
/**
* sends a message to a
* #param ID
* #param input
*/
public synchronized void handle(int ID, String input)
{
StringTokenizer t = new StringTokenizer(input);
String[] arg = new String[t.countTokens()];
for(int i=0; t.hasMoreElements(); i++)
arg[i] = t.nextToken(",");
if(arg[0] == "new")
switch(input)
{
case".bye":
{
clients[findClient(ID)].send(".bye");
remove(ID);
break;
}
default:
{
for (int i = 0; i < clientCount; i++)
clients[i].send(input);
break;
}
}
}
/**
* sends a message to all clients
* #param input message to send
*/
public void sendAll(String input)
{
for (int i = 0; i < clientCount; i++)
clients[i].send(input);
}
/**
* remove a selected ID
* #param ID ID of client
*/
#SuppressWarnings("deprecation")
public synchronized void remove(int ID)
{
int pos = findClient(ID);
if (pos >= 0)
{
ChatServerThread toTerminate = clients[pos];
log("Removing client thread " + ID + " at " + pos);
if (pos < clientCount-1)
for (int i = pos+1; i < clientCount; i++)
clients[i-1] = clients[i];
clientCount--;
QuitEvent e = new QuitEvent(toTerminate.getID());
e.setGameBreaking(true);
for(QuitHandler a: quitHandlers)
a.quit(e);
try
{
toTerminate.close(); }
catch(IOException ioe)
{
error("Error closing thread: " + ioe);
}
toTerminate.stop();
}
}
private void addThread(Socket socket)
{
if (clientCount < clients.length)
{
log("Client accepted: " + socket);
clients[clientCount] = new ChatServerThread(this, socket);
try
{
clients[clientCount].open();
clients[clientCount].start();
ClientConnectEvent e = new ClientConnectEvent(clients[clientCount],clients[clientCount].getID());
clientCount++;
for(ConnectHandler a: connectHandlers)
a.connect(e);
}
catch(IOException ioe)
{
error("Error opening thread: " + ioe);
}
}
else
error("Client refused: maximum " + clients.length + " reached.");
}
public String toString()
{
return "ChatServer{;host=" + output.getHost() + ";port=" + output.getPort() + ";clients=" + clientCount + ";}";
}
public int getAmountOfClients()
{
return clientCount;
}
public void addConnectHandler(ConnectHandler handler)
{
connectHandlers.add(handler);
}
public void removeConnectHandler(ConnectHandler handler)
{
connectHandlers.remove(handler);
}
public int getMaxClients()
{
return CLIENTMAXIMUM;
}
public void addQuitHandler(QuitHandler quitHandler)
{
quitHandlers.add(quitHandler);
}
public void removeQuitHandler(QuitHandler quithandler)
{
quitHandlers.remove(quithandler);
}
}
ChatServerThread
Used by the ChatServer as client connections
package com.weebly.foxgenesis.src;
import java.net.*;
import java.io.*;
public final class ChatServerThread extends Thread
{
private ChatServer server = null;
private Socket socket = null;
private int ID = -1;
private DataInputStream streamIn = null;
private DataOutputStream streamOut = null;
public ChatServerThread(ChatServer server, Socket socket)
{
super();
this.server = server;
this.socket = socket;
this.ID = socket.getPort();
}
#SuppressWarnings("deprecation")
public void send(String msg)
{
try
{
streamOut.writeUTF(msg);
streamOut.flush();
}
catch(IOException ioe)
{
server.error(ID + " ERROR sending: " + ioe.getMessage());
server.remove(ID);
stop();
}
}
public int getID()
{
return ID;
}
#SuppressWarnings("deprecation")
#Override
public void run()
{
server.log("Server Thread " + ID + " running.");
while (true)
{
try
{
server.handle(ID, streamIn.readUTF());
}
catch(IOException ioe)
{
server.error(ID + " ERROR reading: " + ioe.getMessage());
server.remove(ID);
stop();
}
}
}
public void open() throws IOException
{
streamIn = new DataInputStream(new
BufferedInputStream(socket.getInputStream()));
streamOut = new DataOutputStream(new
BufferedOutputStream(socket.getOutputStream()));
}
public void close() throws IOException
{
if (socket != null) socket.close();
if (streamIn != null) streamIn.close();
if (streamOut != null) streamOut.close();
}
}
ClientConnectEvent
package com.weebly.foxgenesis.src;
public class ClientConnectEvent extends ConnectionEvent
{
private final ChatServerThread client;
public ClientConnectEvent(ChatServerThread client, int clientID)
{
super(clientID);
this.client = client;
}
public ChatServerThread getClient()
{
return client;
}
#Override
public boolean isConnectionBreaking(){return false;}
}
ConnectHandler
package com.weebly.foxgenesis.src;
public interface ConnectHandler
{
public void connect(ClientConnectEvent e);
}
ClientQuitEvent
package com.weebly.foxgenesis.src;
public class ClientQuitEvent extends ConnectionEvent
{
public ClientQuitEvent(int clientID)
{
super(clientID);
}
#Override
public boolean isConnectionBreaking()
{
return true;
}
}
QuitHandler
package com.weebly.foxgenesis.src;
public interface QuitHandler
{
public void quit(ClientQuitEvent e);
}
ServerReciever
package com.weebly.foxgenesis.src;
public interface ServerReciever
{
public void handle(String msg);
public void handleError(String msg);
public int getPort();
public int getMaximunClients();
public void handleLog(Object text);
public String getHost();
}
ConnectionEvent
package com.weebly.foxgenesis.src;
public abstract class ConnectionEvent
{
public abstract boolean isConnectionBreaking();
private int clientID;
public ConnectionEvent(int clientID)
{
this.clientID = clientID;
}
public int getClientID()
{
return clientID;
}
}
Step 2:
Connect Server to Bukkit
i have provided an example on how to connect the server to bukkit by making a new plugin.
public class MyPlugin extends JavaPlugin
{
#Override
public void onEnable()
{
ChatServer server = new ChatServer(new ServerReciever()
{
#Override
public void handle(String msg){handleMsg(msg);}
#Override
public void handleError(String msg){handleErr(msg);}
#Override
public int getPort(){return 25567}
#Override
public int getMaximunClients(){return 100;}
#Override
public void handleLog(Object text){log(text);}
#Override
public String getHost(){return "localhost";}
}
}
public void handleLog(Object text)
{
System.out.println(text);
}
public void handelErr(String msg)
{
System.err.println(msg);
}
public void handleMsg(String msg)
{
if(msg.equalsIgnoreCase("reload"))
Bukkit.reloadOrSomething(); //i don't know the void off the top of my head
}
}
Step 3:
Port Forward
if you don't know what that is go ahead and google it. there are some great tutorials online. you want to port forward the port that you set in the code.
Step 4:
Send a message to the Server
i do not know PHP but all you need to do is send a UTF-8 Encoded message to the server's ip on the port that you hard coded above.
Step 5:
ENJOY!
I am really not clear on explaining this requirement but what I need basically is a JSP page that connects to a Unix server and gets the word count of a file and displays on the JSP page. I have looked on various questions here but nothing helped. A sample code would be of much help. Thanks
Kavin, I guess you must have found some other solution or moved on by now. However, I just came across a requirement that led me to this page.
I looked through the somewhat smuckish responses on this page and many others but could not find a simple to use Telnet client at all.
I spent a little bit of time and wrote a simple client on top of Commons Net's solution. Please forgive the System.out and System.err in the code, I got it to barely work.
public static void main(String[] args) throws Exception {
SimpleTelnetClient client = new SimpleTelnetClient("localhost", 2323);
client.connect();
String result = client.waitFor("login:");
System.out.println("Got " + result);
client.send("username");
result = client.waitFor("Password:");
System.out.println("Got " + result);
client.send("password");
client.waitFor("#");
client.send("ls -al");
result = client.waitFor("#");
System.out.println("Got " + result);
client.send("exit");
}
Not sure if it will help you anymore, but perhaps it could be a starting point for others.
import java.io.InputStream;
import java.io.PrintStream;
import java.util.concurrent.BlockingQueue;
import java.util.concurrent.CountDownLatch;
import java.util.concurrent.LinkedBlockingQueue;
import org.apache.commons.net.telnet.EchoOptionHandler;
import org.apache.commons.net.telnet.InvalidTelnetOptionException;
import org.apache.commons.net.telnet.SuppressGAOptionHandler;
import org.apache.commons.net.telnet.TelnetClient;
import org.apache.commons.net.telnet.TerminalTypeOptionHandler;
public class SimpleTelnetClient {
static class Responder extends Thread {
private StringBuilder builder = new StringBuilder();
private final SimpleTelnetClient checker;
private CountDownLatch latch;
private String waitFor = null;
private boolean isKeepRunning = true;
Responder(SimpleTelnetClient checker) {
this.checker = checker;
}
boolean foundWaitFor(String waitFor) {
return builder.toString().contains(waitFor);
}
public synchronized String getAndClearBuffer() {
String result = builder.toString();
builder = new StringBuilder();
return result;
}
#Override
public void run() {
while (isKeepRunning) {
String s;
try {
s = checker.messageQueue.take();
} catch (InterruptedException e) {
break;
}
synchronized (Responder.class) {
builder.append(s);
}
if (waitFor != null && latch != null && foundWaitFor(waitFor)) {
latch.countDown();
}
}
}
public String waitFor(String waitFor) {
synchronized (Responder.class) {
if (foundWaitFor(waitFor)) {
return getAndClearBuffer();
}
}
this.waitFor = waitFor;
latch = new CountDownLatch(1);
try {
latch.await();
} catch (InterruptedException e) {
e.printStackTrace();
return null;
}
String result = null;
synchronized (Responder.class) {
result = builder.toString();
builder = new StringBuilder();
}
return result;
}
}
static class TelnetReader extends Thread {
private final SimpleTelnetClient checker;
private final TelnetClient tc;
TelnetReader(SimpleTelnetClient checker, TelnetClient tc) {
this.checker = checker;
this.tc = tc;
}
#Override
public void run() {
InputStream instr = tc.getInputStream();
try {
byte[] buff = new byte[1024];
int ret_read = 0;
do {
ret_read = instr.read(buff);
if (ret_read > 0) {
checker.sendForResponse(new String(buff, 0, ret_read));
}
} while (ret_read >= 0);
} catch (Exception e) {
System.err.println("Exception while reading socket:" + e.getMessage());
}
try {
tc.disconnect();
checker.stop();
System.out.println("Disconnected.");
} catch (Exception e) {
System.err.println("Exception while closing telnet:" + e.getMessage());
}
}
}
private String host;
private BlockingQueue<String> messageQueue = new LinkedBlockingQueue<String>();
private int port;
private TelnetReader reader;
private Responder responder;
private TelnetClient tc;
public SimpleTelnetClient(String host, int port) {
this.host = host;
this.port = port;
}
protected void stop() {
responder.isKeepRunning = false;
responder.interrupt();
}
public void send(String command) {
PrintStream ps = new PrintStream(tc.getOutputStream());
ps.println(command);
ps.flush();
}
public void sendForResponse(String s) {
messageQueue.add(s);
}
public void connect() throws Exception {
tc = new TelnetClient();
TerminalTypeOptionHandler ttopt = new TerminalTypeOptionHandler("VT100", false, false, true, false);
EchoOptionHandler echoopt = new EchoOptionHandler(true, false, true, false);
SuppressGAOptionHandler gaopt = new SuppressGAOptionHandler(true, true, true, true);
try {
tc.addOptionHandler(ttopt);
tc.addOptionHandler(echoopt);
tc.addOptionHandler(gaopt);
} catch (InvalidTelnetOptionException e) {
System.err.println("Error registering option handlers: " + e.getMessage());
}
tc.connect(host, port);
reader = new TelnetReader(this, tc);
reader.start();
responder = new Responder(this);
responder.start();
}
public String waitFor(String s) {
return responder.waitFor(s);
}
}
Why wouldn't you just use an open source telnet client. There is bound to be several to choose from. Google lists many.
I want to save and store simple mail objects via serializing, but I get always an error and I can't find where it is.
package sotring;
import java.io.*;
import java.text.DateFormat;
import java.text.SimpleDateFormat;
import java.util.*;
import com.sun.org.apache.bcel.internal.generic.INEG;
public class storeing {
public static void storeMail(Message[] mail){
try {
ObjectOutputStream out = new ObjectOutputStream(new FileOutputStream("mail.ser"));
out.writeObject(mail);
out.flush();
out.close();
} catch (IOException e) {
}
}
public static Message[] getStoredMails(){
try
{
ObjectInputStream in = new ObjectInputStream(new FileInputStream("mail.ser"));
Message[] array = (Message[]) in.readObject() ;
for (int i=0; i< array.length;i++)
System.out.println("EMail von:"+ array[i].getSender() + " an " + array[i].getReceiver()+ " Emailbetreff: "+ array[i].getBetreff() + " Inhalt: " + array[i].getContent());
System.out.println("Size: "+array.length); //return array;
in.close();
return array;
}
catch(IOException ex)
{
ex.printStackTrace();
return null;
}
catch(ClassNotFoundException ex)
{
ex.printStackTrace();
return null;
}
}
public static void main(String[] args) {
User user1 = new User("User1", "geheim");
User user2 = new User("User2", "geheim");
Message email1 = new Message(user1.getName(), user2.getName(), "Test", "Fooobaaaar");
Message email2 = new Message(user1.getName(), user2.getName(), "Test2", "Woohoo");
Message email3 = new Message(user1.getName(), user2.getName(), "Test3", "Okay =) ");
Message [] mails = {email1, email2, email3};
storeMail(mails);
Message[] restored = getStoredMails();;
}
}
Here are the user and message class
public class Message implements Serializable{
static final long serialVersionUID = -1L;
private String receiver; //Empfänger
private String sender; //Absender
private String Betreff;
private String content;
private String timestamp;
private String getDateTime() {
DateFormat dateFormat = new SimpleDateFormat("yyyy/MM/dd HH:mm:ss");
Date date = new Date();
return dateFormat.format(date);
}
Message (String receiver, String sender, String Betreff, String content) {
this.Betreff= Betreff;
this.receiver = receiver;
this.sender = sender;
this.content = content;
this.timestamp = getDateTime();
}
Message() { // Just for loaded msg
}
public String getReceiver() {
return receiver;
}
public void setReceiver(String receiver) {
this.receiver = receiver;
}
public String getSender() {
return sender;
}
public void setSender(String sender) {
this.sender = sender;
}
public String getBetreff() {
return Betreff;
}
public void setBetreff(String betreff) {
Betreff = betreff;
}
public String getContent() {
return content;
}
public String getTime() {
return timestamp;
}
public void setContent(String content) {
this.content = content;
}
}
public class User implements Serializable{
static final long serialVersionUID = -1L;
private String username; //unique Username
private String ipadress; //changes everytime
private String password; //Password
private int unreadMsg; //Unread Messages
private static int usercount;
private boolean online;
public String getName(){
return username;
}
public boolean Status() {
return online;
}
public void setOnline() {
this.online = true;
}
public void setOffline() {
this.online = false;
}
User(String username,String password){
if (true){
this.username = username;
this.password = password;
usercount++;
} else System.out.print("Username not availiable");
}
public void changePassword(String newpassword){
password = newpassword;
}
public void setIP(String newip){
ipadress = newip;
}
public String getIP(){
if (ipadress.length() >= 7){
return ipadress;
} else return "ip address not set.";
}
public int getUnreadMsg() {
return unreadMsg;
}
}
Here is the exception:
exception in thread "main" java.lang.Error: Unresolved compilation problem:
This method must return a result of type Message[]
at sotring.storeing.getStoredMails(storeing.java:22)
at sotring.storeing.main(storeing.java:57)
THANK YOU FOR YOUR HELP!!!!!!!!!!!
The catch clauses need to return something.
public static Message[] getStoredMails(){
try
{
ObjectInputStream in = new ObjectInputStream(new FileInputStream("mail.ser"));
Message[] array = (Message[]) in.readObject() ;
System.out.println("Size: "+array.length); //return array;
in.close();
return array;
}
catch(IOException ex)
{
ex.printStackTrace();
}
catch(ClassNotFoundException ex)
{
ex.printStackTrace();
}
return null; //fix
}
If an exception occurs, you never get to the return statement in getStoredMails. You need to either throw the exception you catch (possibly wrapping it in another more descriptive exception) or just return null at the end of the method. It really depends on what you want to do if there's an error.
Oh, and your in.close() should be in a finally block. Otherwise, it is possible that you could read the data fine but then throw it away if you can't close the stream.
On a different note, have you considered a third-party serializer library?
I'm using Simple right now for a project, and it seems to do stuff just fine with very little effort.
in the exception handling blocks of the getStoredMails method you do not return anything.
Suggested modification:
public static Message[] getStoredMails(){
try
{
ObjectInputStream in = new ObjectInputStream(new FileInputStream("mail.ser"));
Message[] array = (Message[]) in.readObject() ;
System.out.println("Size: "+array.length); //return array;
in.close();
return array;
}
catch(IOException ex)
{
ex.printStackTrace();
}
catch(ClassNotFoundException ex)
{
ex.printStackTrace();
}
return null;
}
I modified the source. I added "return null" in exception and the for loop the output in the function. And the function gives me the right output but then throws it the exception.