how to disconnect client if it is already connected - java

I am using smack API & made 2 client using java, I am using prosody XMPP server on windows platform this is my code (prosody is quite similar to open-fire server)
import java.util.Collection;
import org.jivesoftware.smack.Chat;
import org.jivesoftware.smack.ConnectionConfiguration;
import org.jivesoftware.smack.MessageListener;
import org.jivesoftware.smack.Roster;
import org.jivesoftware.smack.RosterEntry;
import org.jivesoftware.smack.SASLAuthentication;
import org.jivesoftware.smack.XMPPConnection;
import org.jivesoftware.smack.XMPPException;
import org.jivesoftware.smack.packet.Message;
public class TextMessageReceive implements MessageListener {
XMPPConnection connection;
public void login(String userName, String password)throws XMPPException{
ConnectionConfiguration config = new ConnectionConfiguration("localhost",5222,"example.com");
config.setSASLAuthenticationEnabled(true);
config.setSecurityMode(ConnectionConfiguration.SecurityMode.disabled);
SASLAuthentication.supportSASLMechanism("PLAIN", 0);
connection = new XMPPConnection(config);
//connection.connect();
// System.out.println("Connected to " + connection.getHost());
//connection.login(userName, password);
onTimerExpiry(userName, password);
System.out.println("Logged in as " + connection.getUser());
}
public void onTimerExpiry(String userName, String password) {
if (connection != null && connection.isConnected()) {
connection.disconnect();
System.out.println("disconnecting...................");
}
try{
if (connection != null) {
connection.connect();
System.out.println("Logged in as " + connection.getHost());
connection.login(userName, password);
System.out.println("Logged in as " + connection.getUser());
}
}catch(XMPPException e){
e.printStackTrace();
}
}
public void sendMessage(String message, String to) throws XMPPException{
Chat chat = connection.getChatManager().createChat(to, this);
chat.sendMessage(message);
System.out.println("message= "+message+ " received from " +to );
}
public void displayBuddyList(){
Roster roster = connection.getRoster();
Collection<RosterEntry> entries = roster.getEntries();
System.out.println("\n\n" + entries.size() + " buddy(ies):");
for(RosterEntry r:entries){
System.out.println(r.getUser());
}
}
public void disconnect(){
connection.disconnect();
}
public void processMessage(Chat chat, Message message){
System.out.println("Inside the process message");
String string =message.getBody();
String from=message.getFrom();
// byte[] byteArray = Base64.decodeBase64(string.getBytes());
// if(message.getType() == Message.Type.chat)
// {
//// // Print the decoded string
// String decodedString = new String(byteArray);
// System.out.println( "Decoded message = " + decodedString);
System.out.println("message= "+string+ " received from " +from );
}
public static void main(String args[]) throws XMPPException {
TextMessageReceive c = new TextMessageReceive();
// turn on the enhanced debugger
XMPPConnection.DEBUG_ENABLED = true;
// Enter your login information here
c.login("yuvi", "yuvi");
/*
* Displays the users list
*/
//c.displayBuddyList();
try{
Thread.sleep(30000);
String string ="We are sending message to mhealth";
// byte[] byteArray = Base64.encodeBase64(string.getBytes());
// String encodedString = new String(byteArray);
c.sendMessage(string, "mhealth#example.com");
// Print the encoded string
System.out.println( "Message = " + string);
// c.sendMessage("Message coming from yuvi", "yuvi#inpudw014438a");
}catch (Exception e) {
e.printStackTrace();
}
}
}
actually I am using prosody configure for that particular code if first time I do login then no problem with the code but whenever I am trying to connect second time I am getting exception unless I close the client from telnet admin console.here I made onTimerExpiry() method for disconnecting the client if client is already connect but my client is being disconnect & gave me below exception. guys please tell this right or wrong please suggest me...
The exception I get is:
stream:error (text) at
org.jivesoftware.smack.PacketReader.parsePackets(PacketReader.java:260) at
org.jivesoftware.smack.PacketReader.access$000(PacketReader.java:43) at
org.jivesoftware.smack.PacketReader$1.run(PacketReader.java:70)

I got the answer .I have to call the disconnect() method from main()
public static void main(String args[]){
TextMessageReceive c = new TextMessageReceive();
// turn on the enhanced debugger
XMPPConnection.DEBUG_ENABLED = true;
// Enter your login information here
c.login("yuvi", "yuvi");
c.disconnect();
/*
* Displays the users list
*/
}
this is working & not getting any exception in o/p

Related

How to fix 'Server sending data faster than client can handle, server freezes'

I'm using a java server to facilitate online multiplayer in my game made with GameMaker Studio, the players will send data to the java server which will process the data and send it to the players. The problem is that when a player with a slow internet connection is not being able to handle the amount of data being send to it, it will cause the server to freeze for all players (the server will no longer process any data send by other players).
I have simulated slow internet speeds by using NetLimiter and setting the download speed of one laptop at 5 kb/s, while maintaining proper speed at other laptops. I have tried to send ACK packets from the java server to the client and if it doesn't respond in 1 second no more data will be send to that client (and eventually the client will be kicked). This has reduced the chance of freezing the server, but it will still happen occasionally.
Main.java
import java.net.Socket;
import java.net.SocketAddress;
import java.net.InetSocketAddress;
import java.io.IOException;
import java.util.HashMap;
import java.net.ServerSocket;
import java.net.SocketTimeoutException;
public class Main
{
static ServerSocket serverSocket_;
static HashMap<String, ServerInformation> servers_;
static int verboseLevel_;
static int threadTimeout_;
static int masterPort_;
static int serverNumber_;
static int socketTimeOut_;
static {
Main.serverSocket_ = null;
Main.servers_ = new HashMap<String, ServerInformation>();
Main.verboseLevel_ = 5;
Main.threadTimeout_ = 10;
Main.masterPort_ = 6510;
Main.serverNumber_ = 1;
Main.socketTimeOut_ = 6000;
}
public static void main(final String[] args) {
try {
setupServerAndCleanup(Main.masterPort_);
while (true) {
handleIncomingConnection();
}
}
catch (IOException e) {
e.printStackTrace();
}
}
static void setupServerAndCleanup(final int port) throws IOException {
(Main.serverSocket_ = new ServerSocket()).setReuseAddress(true);
Main.serverSocket_.bind(new InetSocketAddress(Main.masterPort_));
System.out.println("Server socket up and running on port " + Main.masterPort_);
Runtime.getRuntime().addShutdownHook(new Thread(new Runnable() {
#Override
public void run() {
if (Main.serverSocket_ != null) {
try {
Main.serverSocket_.close();
System.out.println("Server socket closed, port released");
}
catch (IOException e) {
e.printStackTrace();
}
}
}
}));
}
static void handleIncomingConnection() throws IOException {
final Socket clientSocket = Main.serverSocket_.accept();
clientSocket.setSoTimeout(Main.socketTimeOut_);
final ClientThread client = new ClientThread(clientSocket);
client.start();
}
}
ClientThread.java
Case 1 is the part dealing with sending data to the clients, in particular this line:
thread2.out_.print(msg);
If more data is being send than one client can handle the server will freeze for all other clients as well.
import java.util.Iterator;
import java.io.IOException;
import java.io.Reader;
import java.io.InputStreamReader;
import java.util.regex.Pattern;
import java.io.BufferedReader;
import java.io.PrintWriter;
import java.net.Socket;
import java.net.SocketTimeoutException;
public class ClientThread extends Thread
{
Socket clientSocket_;
String clientIp_;
String serverIp_;
ServerInformation server_;
PrintWriter out_;
BufferedReader in_;
boolean prepareTermination_;
boolean terminated_;
private static final Pattern numberPattern;
static {
numberPattern = Pattern.compile("\\d+");
}
public ClientThread(final Socket sock) {
this.clientSocket_ = sock;
this.clientIp_ = this.clientSocket_.getRemoteSocketAddress().toString();
this.serverIp_ = null;
this.server_ = null;
this.prepareTermination_ = false;
this.terminated_ = false;
}
#Override
public void run() {
try {
this.out_ = new PrintWriter(this.clientSocket_.getOutputStream(), true);
this.in_ = new BufferedReader(new InputStreamReader(this.clientSocket_.getInputStream()));
long lastActionTime = System.currentTimeMillis();
while (true) {
if (this.in_.ready() || System.currentTimeMillis() - lastActionTime >= 1000 * Main.threadTimeout_) {
if (System.currentTimeMillis() - lastActionTime >= 1000 * Main.threadTimeout_) {
//this.logDebugMessage(3, "Thread was killed due to prolonged inactivity (" + Main.threadTimeout_ + " seconds)");
this.terminateThread();
return;
}
final String tempInputLine;
if(((tempInputLine = this.in_.readLine()) == null )){
this.terminateThread(); //end thread
return;
}
else
{
lastActionTime = System.currentTimeMillis();
final String inputLine = tempInputLine.trim();
if (ClientThread.numberPattern.matcher(inputLine).matches()){
final int val = Integer.parseInt(inputLine);
switch (val) {
case 1: { //send data to other players
final int parseCount = Integer.parseInt(this.in_.readLine().trim());
final StringBuilder msg = new StringBuilder();
for (int j = 0; j < parseCount; ++j) {
msg.append(String.valueOf(this.in_.readLine().trim()) + "|");
}
for (final ClientThread thread2 : this.server_.ipToClientThread_.values()) {
if (thread2 != this) {
thread2.out_.print(msg);
thread2.out_.flush();
}
}
//this.logDebugMessage(5, "Packet for others: '" + msg.toString() + "'");
break;
}
case 2: { //remove game server
//this.logDebugMessage(1, "A game server has been deleted, ip: " + ipServer);
Main.servers_.remove(this.server_.ip_);
this.serverIp_ = null;
for (final ClientThread thread : this.server_.ipToClientThread_.values()) {
thread.prepareTermination_ = true;
}
this.terminateThread();
return;
}
case 3: { //connect new client
final String ipServer = this.in_.readLine().trim();
final String ipClient = this.in_.readLine().trim();
this.logDebugMessage(1, "A client wishes to connect to a server, client: " + ipClient + ", server: " + ipServer);
final ServerInformation info = Main.servers_.getOrDefault(ipServer, null);
if (info == null) {
System.out.println("Connection to the server failed, no such server in the server list");
this.out_.print("*" + 1 + "|" + 1 + "~" + "|");
this.out_.flush();
break;
}
this.server_ = info;
this.server_.ipToClientThread_.put(ipClient, this);
this.logDebugMessage(1, "Connection success");
this.logDebugMessage(5,"Map: " + this.server_.ipToClientThread_);
this.out_.print("*" + 1 + "|" + 2 + "~" + "|");
this.out_.flush();
break;
}
case 4: { //disconnect client
final String ipClient = this.in_.readLine().trim();
this.server_.ipToClientThread_.remove(ipClient);
this.logDebugMessage(1, String.valueOf(ipClient) + " disconnected from the server at " + this.server_.ip_);
this.serverIp_ = null;
this.terminateThread();
return;
}
case 5: { //host create new game
if (Main.serverNumber_ > 1000000) {
Main.serverNumber_ = 10;
}
Main.serverNumber_ += 1;
final String ipServer = Integer.toString(Main.serverNumber_); //unique server number
final String ipHost = this.in_.readLine().trim(); //host
final String name = this.in_.readLine().trim(); //Server name
final String description = this.in_.readLine().trim(); //class
final String servervar1 = this.in_.readLine().trim(); //max players
final String servervar3 = this.in_.readLine().trim(); //current lap
final String servervar4 = this.in_.readLine().trim(); //total laps
final String servervar5 = this.in_.readLine().trim(); //status
final String servervar6 = this.in_.readLine().trim(); //Password
final String servervar7 = this.in_.readLine().trim(); //Online version
final String servervar8 = this.in_.readLine().trim(); //Game server
final long servervar9 = System.currentTimeMillis(); //server creation time
//this.logDebugMessage(1, "A game server has been registered, ip: " + ipServer + ", name: " + name + ", description: " + description + ", servervar1: " + servervar1);
final ServerInformation gameServer = new ServerInformation(name, servervar1, servervar3, servervar4, servervar5, servervar6, servervar7, servervar8, servervar9, ipHost, ipServer, this.clientSocket_, this.out_, this.in_);
gameServer.description_ = description;
gameServer.ipToClientThread_.put(ipHost, this);
this.server_ = gameServer;
Main.servers_.put(ipServer, gameServer);
this.serverIp_ = ipServer;
break;
}
default: {
this.logDebugMessage(0, "Unrecognized case: '" + inputLine + "', " + val);
break;
}
}
}
else if (inputLine.length() > 0) {
this.logDebugMessage(0, "Unformated '" + inputLine + "'");
if (this.server_ != null) {
this.server_.out_.print(inputLine);
this.server_.out_.flush();
}
}
if (this.prepareTermination_) {
this.terminateThread();
return;
}
continue;
}
}
}
}
catch (SocketTimeoutException e) {
e.printStackTrace();
try {
this.terminateThread();
}
catch (IOException e2) {
e2.printStackTrace();
}
}
catch (IOException e3) {
e3.printStackTrace();
try {
this.terminateThread();
}
catch (IOException e4) {
e4.printStackTrace();
}
}
}
//debug messages
void logDebugMessage(final int requiredVerbose, final String msg) {
if (Main.verboseLevel_ >= requiredVerbose) {
System.out.println("[" + this.clientIp_ + "] " + msg);
}
}
//terminate thread
void terminateThread() throws IOException {
if (!this.terminated_) {
if (this.serverIp_ != null) {
Main.servers_.remove(this.serverIp_);
}
this.clientSocket_.close();
this.in_.close();
this.out_.close();
this.logDebugMessage(3, "Cleanup successful");
this.terminated_ = true;
}
}
}
How to avoid the server from freezing if more data is being send to a client than it can handle, so that the server can continue sending data to the other clients?
Edit
So I have tried using ExecutorService, but I must be doing something completely wrong because no data is being send by the java server.
for (final ClientThread thread2 : this.server_.ipToClientThread_.values()) {
if (thread2 != this) {
executorService = Executors.newSingleThreadExecutor();
executorService.execute(new Runnable() {
public void run() {
thread2.out_.print(msg);
thread2.out_.flush();
}
});
executorService.shutdown();
}
}
It would be great if you could show me how to implement ExecutorService the right way.
If a delay in the client processing doesn't matter, this part should be done in a distinct flow execution for each client :
for (final ClientThread thread2 : this.server_.ipToClientThread_.values()) {
thread2.out_.print(msg);
thread2.out_.flush();
}
For example :
for (final ClientThread thread2 : this.server_.ipToClientThread_.values()) {
if (thread2 != this) {
new Thread(()-> {
thread2.out_.print(msg);
thread2.out_.flush();
})
.start();
}
}
Note that creating Threads has a cost. Using ExecutorService could be a better idea.

How can i make this use multiple threads as clients - who all perform a task each within the switch statement

How can I make this use multiple threads as clients - who all perform a task each within the switch statement? I would also like the threads to perform these tasks and once they have carried them out they stop (currently these tasks are performed from user input).
There are 3 classes the server, client and developer database - which holds a constructor for the 'developer' objects within an ArrayList in the server. This array list is providing the information which is being passed to the clients upon their specific requests.
Here is my code: Client:
import java.io.IOException;
import java.io.ObjectOutputStream;
import java.io.OutputStream;
import java.io.PrintWriter;
import java.net.Socket;
import java.util.*;
public class QuoteOfTheDayClient_2 {
static String devName;
static String devSkill;
static Boolean devHire;
static Socket echoSocket = null; // holds the Socket object
static Scanner fromServer = null; // input stream from remote host
static Scanner fromServer1 = null; // input stream from remote host
static PrintWriter toServer = null; // output stream to remote host
static PrintWriter toServer1 = null; // output stream to remote host
static Scanner stdIn = new Scanner(System.in);
static String remoteServer = "localhost"; // are you 'local'?!
//String remoteServer = "193.61.190.96"; // remote host is not 'local'!
static int port;
static String reply;// holds reply from remote host
public static void searchForSkill(String skill) {
toServer.println(1);
String quoteNum = "php"; //Search for a specific coding language -
Specific to the entered parameters
System.out.println("Searching for Skill: " + skill + " in Developer
Database");
toServer.println(quoteNum);
while (!(reply = fromServer.nextLine()).isEmpty()) {
// System.out.println(reply1);
System.out.println(reply);// print reply to screen
}
fromServer.nextLine(); // Consume the newline
System.out.println();
}
public static void addDeveloper(String name, String skill,boolean
hire)
{
toServer.println(2);
System.out.println("Add Developer to system ");
stdIn.nextLine(); // flush newline
String quoteString = name;//stdIn.nextLine();
String quoteString1 = skill;//stdIn.nextLine();
boolean quoteString2 = hire;//stdIn.nextLine();
toServer.println(quoteString);
toServer.println(quoteString1);
toServer.println(quoteString2);
fromServer.next();
System.out.println("\nDeveloper entered: " + quoteString + "\n");
while (!(reply = fromServer.nextLine()).isEmpty()) {
// System.out.println(reply1);
System.out.println(reply);// print reply to screen
}
}
public static void checkAvailability(String developerName) {
try {
toServer.println(3);
System.out.println("Send Developer Name to Find Availability:
");
String quoteDel = developerName;
toServer.println(quoteDel);
while (!(reply = fromServer.nextLine()).isEmpty()) {
// System.out.println(reply1);
System.out.println(reply);// print reply to screen
}
} catch (NoSuchElementException e) {
}
}
public static void hireDeveloper(String name) {
toServer.println(4);
String quoteNum = name; //Search for a specific coding language -
Specific to the entered parameters
System.out.println("Searching for: " + name + " in Developer
Database");
toServer.println(quoteNum);
while (!(reply = fromServer.nextLine()).isEmpty()) {
// System.out.println(reply1);
System.out.println(reply);// print reply to screen
}
fromServer.nextLine(); // Consume the newline
System.out.println();
}
public static void printAllDevelopers(){
toServer.println(5);
while (!(reply = fromServer.nextLine()).isEmpty()) {
// System.out.println(reply1);
System.out.println(reply);// print reply to screen
}
fromServer.nextLine(); // Consume the newline
System.out.println();
}
public static void clientMenu(){
try {
port = 4444; // 17 for localhost
echoSocket = new Socket(remoteServer, port);
fromServer = new Scanner(echoSocket.getInputStream());
fromServer1 = new Scanner(echoSocket.getInputStream());
toServer = new PrintWriter(echoSocket.getOutputStream(), true);
toServer1 = new PrintWriter(echoSocket.getOutputStream(),
true);
OutputStream os = echoSocket.getOutputStream();
ObjectOutputStream oos = new ObjectOutputStream(os);
} catch (Exception e) {
System.err.println("Exception: " + e);
System.exit(1);
} // try-catch
String reply;// holds reply from remote host
int command;
String reply1;
String devName="David Blaine";
String devSkill="Java";
System.out.println("Enter command: 1:Search Skill 2:Add
Developer 3:Search Availability 4:Hire Developer 5:Show all
Developers 6:Exit");
command = 0;
command = command+1;
// while (command != 0) {
for(int i=1;i<6;i++) {
command=i;
switch (i) {
case 1: {
// get quote
searchForSkill("PHP");
break;
}
case 2: {
// add quote
addDeveloper("David Blaine", "Java", true);
break;
}
case 3: {
// delete quote
checkAvailability("David Ferguson");
break;
}
case 4: {
hireDeveloper("Thompson");
break;
}
case 5: {
printAllDevelopers();
}
case 6: {
System.exit(6);
}
default:
System.out.println("*** Command not recognised ***");
break;
}
System.out.println("Enter command: 1:Search Skill 2:Add Developer
3:Search Availability 4:Hire Developer 5:Show all Developers
6:Exit");
command = stdIn.nextInt();
//}
}
toServer.println(command);
try {
echoSocket.close();
} catch (IOException e) {
e.printStackTrace();
}
fromServer.close();
toServer.close();
stdIn.close();
}
public static void main(String[] args) throws IOException {
clientMenu();
} // main
} // EchoClient
Server code:
import java.io.IOException;
import java.io.ObjectInputStream;
import java.io.PrintWriter;
import java.lang.reflect.Array;
import java.net.ServerSocket;
import java.net.Socket;
import java.util.ArrayList;
import java.util.InputMismatchException;
import java.util.List;
import java.util.Scanner;
public class QuoteOfTheDayServer_2 {
private static DeveloperDatabase[] developerList = new
DeveloperDatabase[7];
static DeveloperDatabase temp []=new DeveloperDatabase[7];
static String userAddDevName;
static String userAddCodeSkills;
static Boolean userAddHireAvailability;
static int command;
static List<DeveloperDatabase> list = new
ArrayList<DeveloperDatabase>(){
{
add(new DeveloperDatabase(1,"David Ferguson", "Java",
true));
add(new DeveloperDatabase(2,"Grant Thompson", "Java",
true));
add(new DeveloperDatabase(3,"Craig Jackson", "C++", true));
add(new DeveloperDatabase(4,"Kevin James","C++", true));
add(new DeveloperDatabase(5,"Greg Troupe", "Python",
true));
add(new DeveloperDatabase(6,"James Smith", "Python",
true));
add(new DeveloperDatabase(7,"Jamie Richie", "PHP", true));
add(new DeveloperDatabase(8,"Rory McGrattan", "PHP",
false));
}
};
public static String printJava(){
String message="";
for (int i=0;i<2;i++){
message +=list.get(i).toString();
message+=" \n";
}
return message;
}
public static String printC(){
String message="";
for (int i=2;i<4;i++){
message +=list.get(i).toString();
message+=" \n";
}
return message;
}
public static String printPy(){
String message="";
for (int i=4;i<6;i++){
message +=list.get(i).toString();
message+=" \n";
}
return message;
}
public static String printPHP(){
String message="";
for (int i=6;i<8;i++){
message +=list.get(i).toString();
message+=" \n";
}
return message;
}
public static void addDeveloper(String name,String
codeSkill,Boolean hire){
userAddDevName=name;
userAddCodeSkills = codeSkill;
userAddHireAvailability = hire;
System.out.println("*********Adding Developer***********");
System.out.println(userAddDevName+ " has been added to the
system");
list.add(new DeveloperDatabase(9,
userAddDevName,userAddCodeSkills, userAddHireAvailability));
System.out.println(list.get(8));
}//addDeveloper
public static String checkAvail(String clientMessage){
String message="";
for (int i=0;i<list.size();i++){
if
(clientMessage.equalsIgnoreCase(list.get(i).getDeveloperName())) {
message+= list.get(i).toString();
message+="\n";
}
} return message;
}
public static String printAllDevelopers(){
String message="";
for (int i=0;i<8;i++){
message +=list.get(i).toString();
message+=" \n";
}
return message;
}
public static void main(String[] args) throws IOException {
// Wrap the standard System.in stream with a Scanner so that
Scanner stdIn = new Scanner(System.in);
Scanner fromClient = null;
PrintWriter toClient = null;
PrintWriter toClient1=null;
int pNum = 4444;
ServerSocket sSocket = null;
Socket cSocket = null;
try {
sSocket = new ServerSocket(pNum);
} catch (IOException e) {
System.out.println("Couldn't listen on port: " + pNum + ";
" +
e);
System.exit(1);
}
// Continuously wait for client; accept them; and send a quote
to
them.
while (true) {
try {
System.out.println("Waiting for client ....");
// Blocking 'accept' i.e. wait for a client
cSocket = sSocket.accept();
System.out.println("Client connected from: " +
cSocket.getInetAddress());
// Set up the output stream for the server, i.e. a
PrintWriter stream
toClient = new PrintWriter(cSocket.getOutputStream(),
true);
toClient1 = new PrintWriter(cSocket.getOutputStream(),
true);
ObjectInputStream ois = new
ObjectInputStream(cSocket.getInputStream());
fromClient = new Scanner(cSocket.getInputStream());
try {
command = fromClient.nextInt();
//fromClient.nextLine();
} catch (InputMismatchException e){
System.out.print("Your selection can only be an
integer!");
}
System.out.println("Received command: " + command + "
from
client at " + cSocket.getInetAddress());
while (command != 0) {
switch (command) {
case 1: // get skills
{
System.out.println("GET skill");
fromClient.nextLine();
String quoteNum =
fromClient.nextLine();//receive from client
if (quoteNum.equalsIgnoreCase("Java")) {
toClient1.println(printJava());
} else if
(quoteNum.equalsIgnoreCase("C++")) {
toClient1.println(printC());
} else if
(quoteNum.equalsIgnoreCase("Python"))
{
toClient.println(printPy());
} else if
(quoteNum.equalsIgnoreCase("PHP")) {
toClient.println(printPHP());
}
else {
toClient.println("No developer with
those
skills found");
}
//
toClient.println(list.equals("Java"));//number -1 for array (0) to
client print
System.out.println("Pushed Developer
number: "
+ quoteNum + " to client at " + cSocket.getInetAddress());
//toClient.println(quotes[quoteNum]); //
return
quote //if "java' { get(0) get(1)
break;
}
case 2: // add quote
{
System.out.println("ADD Developer to
System");
fromClient.nextLine(); // flush newline
String quote = fromClient.next();
fromClient.nextLine();
String quote1 = fromClient.next();
fromClient.nextLine();
boolean quote2 = fromClient.nextBoolean();
toClient.println("The\t*************Developer
has been Added to the Developer Database********");
list.add(new DeveloperDatabase(9, quote,
quote1, quote2));
toClient.println(list.get(8).toString());
//addDeveloper(quote,quote1,quote2);
System.out.println(list.get(8));
//System.out.println("Received quote from
client:" + quote);
quote = quote + "\n\n";
//list.add((quote);
System.out.println("Added Developer: " +
quote);
break;
}
case 3: // Check if Developer is available
{
System.out.println("Check if developer is
Available\n");
fromClient.nextLine();
String quoteNum = fromClient.nextLine();
System.out.println("Checking availability
for:
" + quoteNum);
if (quoteNum.equalsIgnoreCase("Rory
McGrattan")) {
toClient.println("The Developer is not
available for hire");
} else {
toClient.println("The Developer is
available for hire");
}break;
}case 4: {
System.out.println("Hire A Developer");
String quoteNum =fromClient.next();
System.out.println("Client wants to hire:
"+quoteNum);
String message = quoteNum;
for(int i=0;i<list.size();i++){
if
(quoteNum.equalsIgnoreCase(list.get(i).getDeveloperName())){
list.get(i).hireDeveloper();
}//if
}//if
//System.out.println(message);
toClient.println("******* You have Hired:
"+
message+" ********");
break;
}
case 5: {// Print all Developers
String message="";
for (int i=0;i<8;i++){
message +=list.get(i).toString();
message+=" \n";
}
toClient.println(message);
}
default:
break;
}
try {
//command = fromClient.nextInt();
}catch(InputMismatchException e){
}
System.out.println("Received command: " + command +
"from client at " + cSocket.getInetAddress());
}
// Close all streams
toClient.close();
cSocket.close();
fromClient.close();
stdIn.close();
} catch (IOException e) {
System.out.println("Accept failed: " + pNum + "; " +
e);
System.exit(1);
}
}
} // main
} // QuoteOfTheDayServer_2
DeveloperDatabase code:
public class DeveloperDatabase {
private int id;
private String developerName;
private String codingLanguage;
private boolean freeForHire;
public DeveloperDatabase(){
}
public DeveloperDatabase(int id,String name,String codeSkills,boolean
hire){
this.id = id;
this.developerName = name;
this.codingLanguage=codeSkills;
this.freeForHire=hire;
}
public String toString() {
String message = "\tName: " +developerName;
message += "\n" + "\tCoding Language: "+ codingLanguage+"\n";
if (freeForHire== true) {
message += "\tThe developer is Available! for Hire!\n";
} else {
message += "\tThe developer is not Available for Hire!\n";
}
return message;
}//toString
public boolean getFreeForHire() {
if (freeForHire==true){
System.out.println("The Developer is free to hire!");
}else{
System.out.println("The Developer is not free to hire!");
}
return freeForHire;
}
public String getCodingLanguage() {
return codingLanguage;
}
public void hireDeveloper(){
if (freeForHire==true)
freeForHire = false;
System.out.println(developerName +" is Hired!");
}
public String getDeveloperName() {
return developerName;
}
public static void main(String[] args) {
}//main
}//class
you could use something like
//define executor service to have 5 thread
1)
ExecutorService service=Executors.newFixedThreadPool(5);
2)
//replace move code insde while (command != 0) into a separate class that implements runnable, lets call this Task.
public class Task implements Runnable{
private final Integer command;
public Task(Integer command) {
this.command=command;
}
#Override
public void run() {
//do something, like switch statement
}
}
3) create a helper method, and call this method
public void process(Task t){
service.submit(t);
}

Can anyone tell me why these methods are not running after the first method call? - Java

so basically I have a simple echo server client. What i am wanting to do is run the server then run the client, once the client has been run it should run the methods within it. However, only the first method searchForSkill runs and after this nothing else happens can anyone explain why this is happening or how to ensure the next method called actually runs? I have a developer database class which uses a constructor to create the objects held in the server class. Any help is greatly appreciated.
Server class:
import java.io.PrintWriter;
import java.net.ServerSocket;
import java.net.Socket;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
import java.util.Scanner;
public class Server {
static List<DeveloperDatabase> list = new ArrayList<DeveloperDatabase>(){
{
add(new DeveloperDatabase(1,"David Ferguson", "Java", true));
add(new DeveloperDatabase(2,"Grant Thompson", "Java", true));
add(new DeveloperDatabase(3,"Craig Jackson", "C++", true));
add(new DeveloperDatabase(4,"Kevin James","C++", true));
add(new DeveloperDatabase(5,"Greg Troupe", "Python", true));
add(new DeveloperDatabase(6,"James Smith", "Python", true));
add(new DeveloperDatabase(7,"Jamie Richie", "PHP", true));
add(new DeveloperDatabase(8,"Rory McGrattan", "PHP", false));
}
};
public static String printJava(){
String message="";
for (int i=0;i<2;i++){
message +=list.get(i).toString();
message+=" \n";
}
return message;
}
public static String printC(){
String message="";
for (int i=2;i<4;i++){
message +=list.get(i).toString();
message+=" \n";
}
return message;
}
public static String printPy(){
String message="";
for (int i=4;i<6;i++){
message +=list.get(i).toString();
message+=" \n";
}
return message;
}
public static String printPHP(){
String message="";
for (int i=6;i<8;i++){
message +=list.get(i).toString();
message+=" \n";
}
return message;
}
// Main
public static void main(String[] args) {
ServerSocket listenSocket;
Socket s;
PrintWriter toClient = null;
Scanner fromClient = null;
int port; // holds port server will listen on
String userInput; // holds a line typed by the user
System.out.print("Server - port to listen on: ");
//port = stdIn.nextInt(); // get port number from user
port = 4444; // get port number from user
System.out.println(port);
try {
listenSocket = new ServerSocket(port);
System.out.println("Waiting for client...");
s = listenSocket.accept();
toClient = new PrintWriter(s.getOutputStream(), true);
fromClient = new Scanner(s.getInputStream());
int inputLine;
do {
inputLine = fromClient.nextInt();
switch (inputLine) {
case 1: // get skills
{
System.out.println("GET skill");
fromClient.nextLine();
String quoteNum = fromClient.nextLine();//receive from client
if (quoteNum.equalsIgnoreCase("Java")) {
toClient.println(printJava());
} else if (quoteNum.equalsIgnoreCase("C++")) {
toClient.println(printC());
} else if (quoteNum.equalsIgnoreCase("Python")) {
toClient.println(printPy());
} else if (quoteNum.equalsIgnoreCase("PHP")) {
toClient.println(printPHP());
}
else {
toClient.println("No developer with those skills found");
}
// toClient.println(list.equals("Java"));//number -1 for array (0) to client print
System.out.println("Pushed Developer number: " + quoteNum + " to client at " + s.getInetAddress());
//toClient.println(quotes[quoteNum]); // return quote //if "java' { get(0) get(1)
break;
}
case 2: // add quote
{
System.out.println("ADD Developer to System");
fromClient.nextLine(); // flush newline
String quote = fromClient.next();
fromClient.nextLine();
String quote1 = fromClient.next();
fromClient.nextLine();
boolean quote2 = fromClient.nextBoolean();
toClient.println("The\t*************Developer has been Added to the Developer Database********");
list.add(new DeveloperDatabase(9, quote, quote1, quote2));
toClient.println(list.get(8).toString());
//addDeveloper(quote,quote1,quote2);
System.out.println(list.get(8));
//System.out.println("Received quote from client:" + quote);
quote = quote + "\n\n";
//list.add((quote);
System.out.println("Added Developer: " + quote);
break;
}
case 3: // Check if Developer is available
{
System.out.println("Check if developer is Available\n");
fromClient.nextLine();
String quoteNum = fromClient.nextLine();
System.out.println("Checking availability for: " + quoteNum);
if (quoteNum.equalsIgnoreCase("Rory McGrattan")) {
toClient.println("The Developer is not available for hire");
} else {
toClient.println("The Developer is available for hire");
}break;
}case 4: {
System.out.println("Hire A Developer");
String quoteNum =fromClient.next();
System.out.println("Client wants to hire: "+quoteNum);
String message = quoteNum;
for(int i=0;i<list.size();i++){
if (quoteNum.equalsIgnoreCase(list.get(i).getDeveloperName())){
list.get(i).hireDeveloper();
}//if
}//if
//System.out.println(message);
toClient.println("******* You have Hired: "+ message+" ********");
break;
}
case 5: {// Print all Developers
String message="";
for (int i=0;i<8;i++){
message +=list.get(i).toString();
message+=" \n";
}
toClient.println(message);
}
default:
break;
}
} while (fromClient.hasNextLine());
// Close all streams
System.out.println("Closing Server...");
toClient.close();
fromClient.close();
s.close();
} catch (Exception e) {
System.out.println("Exception: " + e);
System.exit(1);
}
} // run
} // Server
Client class:
import java.io.IOException;
import java.io.PrintWriter;
import java.net.Socket;
import java.util.NoSuchElementException;
import java.util.Scanner;
public class Client {
static Scanner stdIn = new Scanner(System.in);
static PrintWriter toServer = null; // output stream to remote host
static Scanner fromServer = null; // input stream from remote host
static String reply;// holds reply from remote host
public static void doTasks(){
searchForSkill("PHP");
addDeveloper("David Blaine", "Java", true);
checkAvailability("David Ferguson");
hireDeveloper("Thompson");
printAllDevelopers();
}
private static void searchForSkill(String skill) {
toServer.println(1);
String quoteNum = "php"; //Search for a specific coding language - Specific to the entered parameters
System.out.println("Searching for Skill: " + skill + " in Developer Database");
toServer.println(quoteNum);
while (!(reply = fromServer.nextLine()).isEmpty()) {
// System.out.println(reply1);
System.out.println(reply);// print reply to screen
}
fromServer.nextLine(); // Consume the newline
System.out.println();
}
public static void addDeveloper(String name, String skill,boolean hire) {
toServer.println(2);
System.out.println("Add Developer to system ");
stdIn.nextLine(); // flush newline
String quoteString = name;//stdIn.nextLine();
String quoteString1 = skill;//stdIn.nextLine();
boolean quoteString2 = hire;//stdIn.nextLine();
toServer.println(quoteString);
toServer.println(quoteString1);
toServer.println(quoteString2);
fromServer.next();
System.out.println("\nDeveloper entered: " + quoteString + "\n");
while (!(reply = fromServer.nextLine()).isEmpty()) {
// System.out.println(reply1);
System.out.println(reply);// print reply to screen
}
}
public static void checkAvailability(String developerName) {
try {
toServer.println(3);
System.out.println("Send Developer Name to Find Availability: ");
String quoteDel = developerName;
toServer.println(quoteDel);
while (!(reply = fromServer.nextLine()).isEmpty()) {
// System.out.println(reply1);
System.out.println(reply);// print reply to screen
}
} catch (NoSuchElementException e) {
}
}
public static void hireDeveloper(String name) {
toServer.println(4);
String quoteNum = name; //Search for a specific coding language - Specific to the entered parameters
System.out.println("Searching for: " + name + " in Developer Database");
toServer.println(quoteNum);
while (!(reply = fromServer.nextLine()).isEmpty()) {
// System.out.println(reply1);
System.out.println(reply);// print reply to screen
}
fromServer.nextLine(); // Consume the newline
System.out.println();
}
public static void printAllDevelopers(){
toServer.println(5);
while (!(reply = fromServer.nextLine()).isEmpty()) {
// System.out.println(reply1);
System.out.println(reply);// print reply to screen
}
fromServer.nextLine(); // Consume the newline
System.out.println();
}
public static void main(String[] args) throws IOException {
Socket serverSocket = null; // holds the Socket object
String remoteServer = "localhost"; // remote host is 'local'!
int port;
try {
System.out.print("Server port: ");
//port = stdIn.nextInt(); // get port number from user
port = 4444; // get port number from user
System.out.print(port);
System.out.println("\n");
// Try to connect to remote host machine on port xxxx
serverSocket = new Socket(remoteServer, port);
// Set up the input/output streams to the remote host
toServer = new PrintWriter(serverSocket.getOutputStream(), true);
// Convert the socket's input stream to a 'Scanner'
// to allow 'nextLine' operations to be performed
fromServer = new Scanner(serverSocket.getInputStream());
} catch (Exception e) {
System.err.println("Exception: " + e);
System.exit(1);
} // try-catch
String userInput; // holds a line typed by the user
String name; // to store name
String number; // to store phone number
do {
userInput = "c";
searchForSkill("PHP");
addDeveloper("David Blaine","Java",true);
checkAvailability("Jamie Richie");
hireDeveloper("Jamie Richie");
printAllDevelopers();
//stdIn.nextLine(); // get command from user
} while (!userInput.equalsIgnoreCase("x"));
toServer.println(userInput);
// Close all streams
toServer.close();
fromServer.close();
stdIn.close();
serverSocket.close();
} // main
} // Client
Developer Database class:
/**
* Created by ${Grant} on ${28/09/2017}
* COMMENTS ABOUT PROGRAM HERE
*/
public class DeveloperDatabase {
private int id;
private String developerName;
private String codingLanguage;
private boolean freeForHire;
public DeveloperDatabase(){
}
public DeveloperDatabase(int id,String name,String codeSkills,boolean hire){
this.id = id;
this.developerName = name;
this.codingLanguage=codeSkills;
this.freeForHire=hire;
}
public String toString() {
String message = "\tName: " +developerName;
message += "\n" + "\tCoding Language: "+ codingLanguage+"\n";
if (freeForHire== true) {
message += "\tThe developer is Available! for Hire!\n";
} else {
message += "\tThe developer is not Available for Hire!\n";
}
return message;
}//toString
public boolean getFreeForHire() {
if (freeForHire==true){
System.out.println("The Developer is free to hire!");
}else{
System.out.println("The Developer is not free to hire!");
}
return freeForHire;
}
public String getCodingLanguage() {
return codingLanguage;
}
public void hireDeveloper(){
if (freeForHire==true)
freeForHire = false;
System.out.println(developerName +" is Hired!");
}
public String getDeveloperName() {
return developerName;
}
public static void main(String[] args) {
}//main
}//class
while (!(reply = fromServer.nextLine()).isEmpty()) {
// System.out.println(reply1);
System.out.println(reply);// print reply to screen
}
You are receiving a response, stopping you from exiting the while loop.

Calling an AS400 RPG program from JAVA

I am trying to call an RPG Logon program on an AS400 system from JAVA. The issue is whenever I give incorrect parameters, I get a response, such as user ID is incorrect, password is incorrect. When I give an incorrect path to the program, I do get the response saying "Object does not exist." However, when all the parameters are right, I don't get any response and the java program keep running without ending. What could be wrong? Code below:
import com.ibm.as400.access.AS400;
import com.ibm.as400.access.AS400Message;
import com.ibm.as400.access.AS400SecurityException;
import com.ibm.as400.access.ErrorCompletingRequestException;
import com.ibm.as400.access.ObjectDoesNotExistException;
import com.ibm.as400.access.ProgramCall;
import com.ibm.as400.access.ProgramParameter;
import java.beans.PropertyVetoException;
import java.io.IOException;
/**
* Test program to test the RPG call from Java.
*/
public class CallingAS400PGM {
private static final String HOST = "xxxxxx";
private static final String UID = "yyyyyyy";
private static final String PWD = "zzzzzzz";
public static void main(String[] args) {
String input = "testuser";
String fullProgramName = "/QSYS.lib/SEOBJP10.lib/LOGON.pgm";
AS400 as400 = null;
byte[] inputData;
byte[] outputData;
ProgramParameter[] parmList;
ProgramCall programCall;
try {
// Create an AS400 object
as400 = new AS400(HOST, UID, PWD);
// Create a parameter list
// The list must have both input and output parameters
parmList = new ProgramParameter[2];
// Convert the Strings to IBM format
inputData = input.getBytes("IBM285");
// Create the input parameter
parmList[0] = new ProgramParameter(inputData);
// Create the output parameter
//Prarameterised Constructor is for the OUTPUT LENGTH. here it is 10
parmList[1] = new ProgramParameter(10);
/**
* Create a program object specifying the name of the program and
* the parameter list.
*/
programCall = new ProgramCall(as400);
programCall.setProgram(fullProgramName, parmList);
// Run the program.
if (!programCall.run()) {
/**
* If the AS/400 is not run then look at the message list to
* find out why it didn't run.
*/
AS400Message[] messageList = programCall.getMessageList();
for (AS400Message message : messageList) {
System.out.println(message.getID() + " - " + message.getText());
}
} else {
/**
* Else the program is successfull. Process the output, which
* contains the returned data.
*/
System.out.println("CONNECTION IS SUCCESSFUL");
outputData = parmList[1].getOutputData();
String output = new String(outputData, "IBM285").trim();
System.out.println("Output is " + output);
}
} catch (PropertyVetoException | AS400SecurityException | ErrorCompletingRequestException | IOException | InterruptedException | ObjectDoesNotExistException e) {
System.err.println(":: Exception ::" + e.toString());
} finally {
try {
// Make sure to disconnect
if (as400 != null) {
as400.disconnectAllServices();
}
} catch (Exception e) {
System.err.println(":: Exception ::" + e.toString());
}
}
}
}
Carefully think about what parameter type,number of parameters are accepting from AS400 RPG program, and use communication only USERID.
import com.ibm.as400.access.AS400;
import com.ibm.as400.access.AS400Message;
import com.ibm.as400.access.AS400Text;
import com.ibm.as400.access.ProgramCall;
import com.ibm.as400.access.ProgramParameter;
public class CallingAS400PGM {
private static final String HOST = "192.168.1.1";//AS400 IP
private static final String UID = "UNAME"; //userid
private static final String PWD = "PWORD"; //password
public static void main(String[] args) {
//AS400 RPG progam path
String fullProgramName = "/QSYS.LIB/PBFORM12.LIB/PBFORM12CL.PGM";
AS400 as400 = null;
ProgramParameter[] parmList;//parameter list witch is accepting AS400 RPG program
ProgramCall programCall;
try {
// Create an AS400 object
as400 = new AS400(HOST, UID, PWD);
// Create a parameter list
// The list must have both input and output parameters
parmList = new ProgramParameter[2];
// Convert the Strings to IBM format
AS400Text nametext1 = new AS400Text(2);
AS400Text nametext2 = new AS400Text(200);
// Create the input parameter // get the exact patameter type and
length, if not this not be working
parmList[0] = new ProgramParameter(nametext1.toBytes("1"),2);
parmList[1] = new ProgramParameter(nametext2.toBytes("Ravinath
Fernando"),200);
// Create the output parameter
programCall = new ProgramCall(as400);
programCall.setProgram(fullProgramName, parmList);
if (!programCall.run()) {
/**
* If the AS/400 is not run then look at the message list to
* find out why it didn't run.
*/
AS400Message[] messageList = programCall.getMessageList();
for (AS400Message message : messageList) {
System.out.println(message.getID() + " - " + message.getText());
}
} else {
System.out.println("success");
/**
* Else the program is successfull. Process the output, which
* contains the returned data.
*/
//use same parameter type which will be return from AS400 program
AS400Text text1 = new AS400Text(2);
System.out.println(text1.toObject(parmList[0].getOutputData()));
AS400Text text2 = new AS400Text(200);
System.out.println(text2.toObject(parmList[1].getOutputData()));
}
as400.disconnectService(AS400.COMMAND);
//-----------------------
} catch (Exception e) {
e.printStackTrace();
System.err.println(":: Exception ::" + e.toString());
} finally {
try {
// Make sure to disconnect
if (as400 != null) {
as400.disconnectAllServices();
}
} catch (Exception e) {
System.err.println(":: Exception ::" + e.toString());
}
}
}
}

Java Chat Server

FYI This is homework. I have to build a Java Chat server. I have been able to build a server which communicates with 1 client. But I need this to communicate with multiple users.
A user is supposed to type in the person's name they wish to talk to followed by a dash (-) and then the message to be sent. I am able to get users signed on but I am not able to get the list of users to print out or the messages to send to other users. Here is the server code:
/**
Threaded Server
*/
import java.net.ServerSocket;
import java.net.Socket;
import java.util.Scanner;
import java.io.PrintWriter;
import java.util.HashMap;
import java.util.Set;
public class ThreadedServer
{
public static void main( String[] args) throws Exception
{
HashMap<String, Socket> users = new HashMap<String, Socket>( );
ServerSocket server = new ServerSocket(5679);
System.out.println( "THE CHAT SERVER HAS STARTED! =)" );
while(true)
{
Socket client = server.accept();
ThreadedServer ser = new ThreadedServer();
ClientFromThread cft =ser.new ClientFromThread(client);
String name = cft.getUserName();
users.put( name, client );
cft.giveUsersMap( users );
//cft.giveOnlineUsers( ); //DOES NOT WORK YET!!!!
System.out.println("Threaded server connected to "
+ client.getInetAddress() + " USER: " + name );
}
}
//***************************************************************************************************
class ClientFromThread extends Thread
{
private Socket client;
private Scanner fromClient;
private PrintWriter toClient;
private String userName;
HashMap<String, Socket> users;
public ClientFromThread( Socket c ) throws Exception
{
client = c;
fromClient = new Scanner( client.getInputStream() );
toClient = new PrintWriter( client.getOutputStream(), true );
userName = getUser();
start();
}
public void giveUsersMap( HashMap<String, Socket> users )
{
this.users = users;
}
//THIS DOESNT WORK YET... IT PRINTS THE FIRST LINE BUT NOT THE LIST
public void giveOnlineUsers()
{
toClient.println("These users are currently online:");
Set<String> userList = users.keySet();
String[] userNames = null;
userList.toArray( userNames );
for( int i = 0; i< userNames.length; i++ )
{
toClient.println(userNames[i]);
}
}
public String getUserName()
{
return userName;
}
private String getUser()
{
String s = "";
while( (s.length() < 1) || (s == null) )
{
toClient.println("What is your first name? ");
s=fromClient.nextLine().trim();
}
toClient.println("Thank You! Welcome to the chat room " + s + ".");
return s.toUpperCase();
}
public void run()
{
String s = null;
String toUser;
String mesg;
while( (s=fromClient.nextLine().trim()) != null )
{
if( s.equalsIgnoreCase( "END" )) break;
for( int i=0; i<s.length(); i++)
{
if( s.charAt(i) == '-' )
{
toUser = s.substring( 0, i ).trim().toUpperCase();
mesg = s.substring( i+1 ).trim();
Socket client = users.get( toUser );
try
{
ClientToThread ctt = new ClientToThread(client);
ctt.sendMesg( mesg, toUser );
ctt.start();
}
catch(Exception e){e.printStackTrace();}
break;
}
if( (i+1) == s.length() )
{
toClient.println("Sorry the text was invalid. Please enter a user name " +
"followed by a dash (-) then your message.");
}
}
}
try
{
fromClient.close();
toClient.close();
client.close();
}
catch(Exception e){e.printStackTrace();}
}
} //end class ClientFromThread
//***************************************************************************************************
class ClientToThread extends Thread
{
private Socket client;
private PrintWriter toClient;
private String mesg;
public ClientToThread( Socket c ) throws Exception
{
client = c;
toClient = new PrintWriter( client.getOutputStream(), true );
}
public void sendMesg( String mesg, String userName )
{
this.mesg = userName + ": " + mesg;
}
public void run()
{
toClient.println(mesg);
try
{
toClient.close();
client.close();
}
catch(Exception e){e.printStackTrace();}
}
} //end class ClientToThread
//***************************************************************************************************
} //end class ThreadedServer
Here is the Client code"
import java.net.Socket;
import java.io.BufferedReader;
import java.io.InputStreamReader;
import java.io.PrintWriter;
public class ReverseClient
{
public static void main( String[] args ) throws Exception
{
String line = null;
Socket server= new Socket( "10.0.2.103", 5679);
System.out.println( "Connected to host: " + server.getInetAddress() );
BufferedReader fromServer = new BufferedReader(
new InputStreamReader(server.getInputStream()) );
PrintWriter toServer = new PrintWriter( server.getOutputStream(), true );
BufferedReader input = new BufferedReader(
new InputStreamReader(System.in) );
while( (line=input.readLine()) !=null )
{
toServer.println(line);
System.out.println( fromServer.readLine() );
}
fromServer.close();
toServer.close();
input.close();
server.close();
}
}
Here is the console output (the top is the server, bottom is the client):
I am getting errors (as shown in the image above) and the messages are not sending. Any suggestions on how to take care of these issues?
So far I found this to be a problem, but I don't think this is the only problem..
This will help the NoSuchElementException
On around line 90 Change this...
while( (s=fromClient.nextLine().trim()) != null )
{
to this...
while(fromClient.hasNext())
{
s = fromClient.nextLine().trim();
OK just found another problem in ClientToThread.run()... You are closing the client connections after you send the first message. I commented them both out and it seems to be working a little better.
public void run()
{
toClient.println(mesg);
try {
//toClient.close();
//client.close();
}
catch (Exception e) {
e.printStackTrace();
}
}
Your first problem is with the parsing of the message from the user.
You loop through the string, and it has one of two options, either the character is a dash or it is invalid.
So, ideally, you should be getting an invalid message for the number of a characters in the username before the dash.
You should use String.indexOf to determine where the dash is, and then split the message into it's two parts, and if the result of indexOf is -1 then it is an invalid message.

Categories