Java GUI app,server reads only first request - java

While making a simple Client-Server GUI app where upon the user's input dimensions of shapes are read and sent back to the server,where the method drawShape is invoked,after sending the initial request("CONNECT##" + NEW) and servers response with (DIM x,y),everything stops,client receives the (DIM x,y )prints ou "1:Draw point\n2:Draw circle\n3.Draw rectangle",and THEN IT WILL NOT SEND BACK TO THE SERVER NO MATTER WHAT I TRY TO OUTPUT,(I tried with a single word) and it did not work.
I really don't know what may be the issue,and I'm struggling with it for several days.
I parsed values,closed scanner,checked scanners,checked loops...
Why is PrintWriter refusing to send OutputStream response to the server?
This is the code:
public static final int TCP_PORT = 8000;
public SGPClientThread(Socket sock) throws IOException {
this.sock = sock;
in = new BufferedReader(new InputStreamReader(sock.getInputStream()),1);
out = new PrintWriter(new BufferedWriter(new OutputStreamWriter(sock.getOutputStream())), true);
start();
}
ETFCanvas can = new ETFCanvas(450, 500);
public void run() {
Scanner scan = new Scanner(System.in);
System.out.println("Send new request by entering '<NEW>'");
String option = "";
option = scan.nextLine();
out.println("CONNECT##" + option);
String read = " ";
try {
read = in.readLine();
} catch (IOException e2) {
// TODO Auto-generated catch block
e2.printStackTrace();
}
if (read.startsWith("<DIM x,y>")) {
System.out.println("1:Draw point\n2:Draw circle\n3.Draw rectangle");
// SO FAR SO GOOD!
> Following code is where the problem occurs,anything I try to print out,will not be
sent to the server,it does not have to be this,you can simply try to send a
word or something simple,not working.
**int choice = scan.nextInt();
switch (choice) {
case 1:
System.out.println("Dimension and color of POINT:x1,y1,color");
System.out.println("Enter X: ");
x = scan.nextInt();
System.out.println("Enter Y: ");
y = scan.nextInt();
do {
try {
System.out.println(
"Enter Color value: ETFCanvas.COLOR_RED;ETFCanvas.COLOR_BLUE;ETFCanvas.COLOR_GREEN");
color = scan.nextInt();
} catch (InputMismatchException e) {
System.out.print("Invalid input ");
}
scan.nextLine(); // clears the buffer
} while (color <= 0);
scan.close();
String iks = String.valueOf(x);
String ipsilon = String.valueOf(y);
String kolor = String.valueOf(color);
out.println("<POINT x,y,c>##" + iks + "##" + ipsilon + "##" + kolor);
break;**
Blockquote
And to keep it short I did not post the rest of the client thread it is just the Case 2 and 3 for drawing Circle and Rectangle,and closed Socket.
Here is my Server Thread code;
ETFCanvas can = new ETFCanvas(450, 500);
public ServerThread(Socket sock, int value) throws IOException {
this.sock = sock;
this.value = value;
// oos = new ObjectOutputStream(sock.getOutputStream());
// ois = new ObjectInputStream(sock.getInputStream());
in = new BufferedReader(new InputStreamReader(sock.getInputStream()),1);
out = new PrintWriter(new BufferedWriter(new OutputStreamWriter(sock.getOutputStream())), true);
start();
}
#Override
public void run() {
String line = "";
//
try {
line = in.readLine();
} catch (IOException e1) {
// TODO Auto-generated catch block
e1.printStackTrace();
}
//
if (line.startsWith("CONNECT##")) {
System.out.println("User sent request " + sock.getRemoteSocketAddress().toString() + line);
String[] content = line.split("##");
req = content[1];
if (req.equals("<NEW>")) {
out.println("<DIM x,y>");
}
} else {
System.out.println("Bad request [" + sock.getRemoteSocketAddress().toString() + "]: " + line);
> Till this part it is working like a charm,and then it will not read a clients
request for drawing
}
if (line.startsWith("<POINT x,y,c>##")) {
System.out.println("User sent request TRY" + sock.getRemoteSocketAddress().toString() + line);
String[] dim = line.split("##");
String dimX = dim[1];
String dimY = dim[2];
String dimC = dim[3];
int x = Integer.parseInt(dimX);
int y = Integer.parseInt(dimY);
int c = Integer.parseInt(dimC);
can.drawPoint(x, y, ETFCanvas.COLOR_RED);
} else if (line.startsWith("<CIRCLE x,y,r,boja>##")) {
String[] dim = line.split("##");
String dimX = dim[1];
String dimY = dim[2];
String dimR = dim[3];
String dimC = dim[4];
int x = Integer.parseInt(dimX);
int y = Integer.parseInt(dimY);
int r = Integer.parseInt(dimR);
int c = Integer.parseInt(dimC);
can.drawCircle(x, y, r, ETFCanvas.COLOR_RED);
} else if (line.startsWith("<RECTANGLE x,y,w,h,boja>##")) {
String[] dim = line.split("##");
String dimX = dim[1];
String dimY = dim[2];
String dimW = dim[3];
String dimH = dim[4];
String dimC = dim[5];
int x = Integer.parseInt(dimX);
int y = Integer.parseInt(dimY);
int w = Integer.parseInt(dimW);
int h = Integer.parseInt(dimH);
int c = Integer.parseInt(dimC);
can.drawRect(x, y, w, h, ETFCanvas.COLOR_RED);
;
try {
in.close();
out.close();
sock.close();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
}

In your server code you read the first line from input but you never read next line anywhere in your code.
You should use while loop to read lines, process them and repeat:
boolean shouldProceed = true;
while (shouldProceed) {
line = in.readLine();
if (line.contains(...)) {
// do something
} else if (line.comtains(...)) {
// do something else
} else {
shouldProceed = false;
}
}

Related

Java Sockets - Sending an object from the server and receiving/displaying it to the client

I am trying to send an object from my server and then receiving it/displaying it on the client side. The object in question has a few parameters tied to it, such as int values and string values. Do I also need to have a version of my server class on the client side in which to store the values from the input stream?
I have tried the following:
Server
public void run() {
int height = 6;
int width = 9;
int moves = height * width;
System.out.println("Connected: " + socket);
try {
Server server = new Server(val1, val2, str1, str2);
Scanner scanner = new Scanner(socket.getInputStream());
PrintWriter printWriter = new PrintWriter(socket.getOutputStream(), true);
ObjectOutputStream serverOutputStream = new ObjectOutputStream(socket.getOutputStream());
ObjectInputStream serverInputStream = new ObjectInputStream(socket.getInputStream());
// while (scanner.hasNextInt()) {
// printWriter.println(scanner.nextInt());
// }
System.out.println(server );
// printWriter.println(server );
serverOutputStream.writeObject(server );
// while (scanner.hasNextInt()) {
for (int player = 0; moves-- > 0; player = 1 - player) {
char symbol = PLAYERS[player];
server.doSomething(symbol, scanner);
// printWriter.println(scanner.nextInt());
System.out.println(server);
// printWriter.println(server);
serverOutputStream.writeObject(server);
if (server.hasWon()) {
System.out.println("\nPlayer " + symbol + " wins!");
return;
}
// }
}
} catch (Exception exception) {
System.out.println("Error: " + socket);
} finally {
try {
socket.close();
} catch (IOException e) {
}
System.out.println("Closed: " + socket);
}
}
Client
public static void main(String[] args) throws Exception {
// if (args.length != 1) {
// System.err.println("Pass the server IP as the sole command line argument");
//
// return;
// }
try (Socket socket = new Socket("127.0.0.1", 59898)) {
System.out.println("Enter a move: ");
Scanner scanner = new Scanner(System.in);
Scanner in = new Scanner(socket.getInputStream());
PrintWriter out = new PrintWriter(socket.getOutputStream(), true);
ObjectInputStream serverInputStream = new ObjectInputStream(socket.getInputStream());
ObjectOutputStream serverOutputStream = new ObjectOutputStream(socket.getOutputStream());
Object object = serverInputStream.readObject();
while (scanner.hasNextLine()) {
out.println(scanner.nextLine());
serverOutputStream.writeObject(object);
}
}
}

Is it possible to store tweets in csv file?

Successfully fetched more than 100 tweets but now i am unable to store those tweets in .csv file ?
Tried for File Handling classes so how can I store the tweets?
public class SentimentAnalysisWithCount {
DoccatModel model;
static int positive = 0;
static int negative = 0;
public static void main(String[] args) throws IOException, TwitterException {
String line = "";
SentimentAnalysisWithCount twitterCategorizer = new SentimentAnalysisWithCount();
twitterCategorizer.trainModel();
ConfigurationBuilder cb = new ConfigurationBuilder();
cb.setDebugEnabled(true)
.setOAuthConsumerKey("--------------------------------------------------")
.setOAuthConsumerSecret("--------------------------------------------------")
.setOAuthAccessToken("--------------------------------------------------")
.setOAuthAccessTokenSecret("--------------------------------------------------");
TwitterFactory tf = new TwitterFactory(cb.build());
Twitter twitter = tf.getInstance();
Query query = new Query("udta punjab");
QueryResult result = twitter.search(query);
int result1 = 0;
for (Status status : result.getTweets()) {
result1 = twitterCategorizer.classifyNewTweet(status.getText());
if (result1 == 1) {
positive++;
} else {
negative++;
}
}
BufferedWriter bw = new BufferedWriter(new FileWriter("C:\\Users\\User\\Desktop\\results.csv"));
bw.write("Positive Tweets," + positive);
bw.newLine();
bw.write("Negative Tweets," + negative);
bw.close();
}
public void trainModel() {
InputStream dataIn = null;
try {
dataIn = new FileInputStream("C:\\Users\\User\\Downloads\\tweets.txt");
ObjectStream lineStream = new PlainTextByLineStream(dataIn, "UTF-8");
ObjectStream sampleStream = new DocumentSampleStream(lineStream);
// Specifies the minimum number of times a feature must be seen
int cutoff = 2;
int trainingIterations = 30;
model = DocumentCategorizerME.train("en", sampleStream, cutoff,
trainingIterations);
} catch (IOException e) {
e.printStackTrace();
} finally {
if (dataIn != null) {
try {
dataIn.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
}
public int classifyNewTweet(String tweet) throws IOException {
DocumentCategorizerME myCategorizer = new DocumentCategorizerME(model);
double[] outcomes = myCategorizer.categorize(tweet);
String category = myCategorizer.getBestCategory(outcomes);
System.out.print("-----------------------------------------------------\nTWEET :" + tweet + " ===> ");
if (category.equalsIgnoreCase("1")) {
System.out.println(" POSITIVE ");
return 1;
} else {
System.out.println(" NEGATIVE ");
return 0;
}
}
}
In this code the tweet which is being displayed on the console that should be stored in .csv file
Please remove your API keys from Stackoverflow. You should not post them in public.
Storing tweets in a CSV is possible and you simply have to enhance your posted code-fragment by adapting the written output. The following code-snippet should give an idea on how to implement it in Java 8:
try(BufferedWriter bw = new BufferedWriter(new FileWriter("C:\\Users\\User\\Desktop\\results.csv"))) {
int positive = 0;
int negative = 0;
StringBuilder sb = new StringBuilder();
for (Status status : result.getTweets()) {
String tweetText = status.getText();
long tweetId = status.getId();
int classificationResult = twitterCategorizer.classifyNewTweet(tweetText);
if (classificationResult == 1) {
positive++;
} else {
negative++;
}
sb.append("ID=").append(tweetId).append(",TEXT=").append(tweetText).append(",classificationResult=").append(classificationResult);
String csvText = sb.toString();
bw.write(csvText);
bw.newLine();
sb.delete(0,csvText);
}
bw.write("##### SUMMARY #####")
bw.write("Positive Tweets," + positive);
bw.newLine();
bw.write("Negative Tweets," + negative);
bw.close();
}catch(IOException e) {
//TODO Exception Handling
}
results.csv would look like:
ID=25125125,TEXT=some fancy text here,classificationResult=1
ID=25146734725,TEXT=some fancy text1 here,classificationResult=0
ID=25127575125,TEXT=some fancy text2 here,classificationResult=1
ID=251258979125,TEXT=some fancy text3 here,classificationResult=0
ID=25125867125,TEXT=some fancy text4 here,classificationResult=1
##### SUMMARY #####
Positive Tweets,3
Negative Tweets,2

Move to next element of array

I need the below code to move to next line and not to restart from first line again
public void actionPerformed(ActionEvent e) {
String getTextArea;
getTextArea = textArea.getText();
String[] arr = getTextArea.split("\\n");
String type = null;
String serial = null;
try {
for(String s : arr) {
if(s.isEmpty()) {
textArea_1.append("Empty line" + '\n');
s = getTextArea;
}
type = s.substring(0, 4);
serial = s.substring(5, 12);
URL url = new URL("blablabla" + type + serial);
BufferedReader in = new BufferedReader(new InputStreamReader(url.openStream()));
String result;
Scanner sc;
sc = new Scanner(in);
while(sc.hasNext()) {
result = sc.next();
if (result.contains("Type:")) {
result = sc.nextLine();
result = sc.nextLine();
result = result.substring(26,30);
textArea_1.append(result + '\t');
}
result = sc.nextLine();
result = sc.nextLine();
result = result.substring(26, 29);
textArea_1.append(result + '\t');
}
}
}
} catch (Exception e2) {
// TODO: handle exception
}
}
});
Here is a picture to show the result
As you see after writing empty line the first line is repeated again !
I think that instead of s = getTextArea; in the if block, you should have continue; to advance to the next element in arr.

TCP sockets returning strange thing in Java

I have socket application that i use for communication with a device.
When i open socket i can read status outputs from the machine.
Machine sends some data which is separated by comma ',' and i need to parse only numbers.
The problem is when i parse the data i recieve numbers but i also recieve "empty" strings.
Here is my code:
void startListenForTCP(String ipaddress) {
Thread TCPListenerThread;
TCPListenerThread = new Thread(new Runnable() {
#Override
public void run() {
Boolean run = true;
String serverMessage = null;
InetAddress serverAddr = null;
BufferedWriter out = null;
int redni = 0;
try {
Socket clientSocket = new Socket(ipaddress, 7420);
try {
mc.pushNumbers("Connection initiated... waiting for outputs!"
+ "\n");
char[] buffer = new char[2];
int charsRead = 0;
out =
new BufferedWriter(new OutputStreamWriter(
clientSocket.getOutputStream()));
BufferedReader in =
new BufferedReader(new InputStreamReader(
clientSocket.getInputStream()));
while ((charsRead = in.read(buffer)) != -1) {
String message = new String(buffer).substring(0, charsRead);
if (message.equals("I,")) {
mc.pushNumbers("\n");
} else {
String m = message;
m = m.replaceAll("[^\\d.]", "");
String stabilo = m;
int length = stabilo.length();
String result = "";
for (int i = 0; i < length; i++) {
Character character = stabilo.charAt(i);
if (Character.isDigit(character)) {
result += character;
}
}
System.out.println("Result:" + m);
}
}
} catch (UnknownHostException e) {
mc.pushNumbers("Unknown host..." + "\n");
} catch (IOException e) {
mc.pushNumbers("IO Error..." + "\n");
} finally {
clientSocket.close();
}
} catch (IOException e) {
e.printStackTrace();
mc.pushNumbers("Connection refused by machine..." + "\n");
}
}
});
TCPListenerThread.start();
}
And the System.out.println(); returns this:
Result:Result:Result:Result:Result:Result:Result:Result:Result:Result:Result:Result:Result:26Result:Result:Result:Result:Result:Result:Result:Result:Result:Result:Result:Result:Result:Result:Result:13
Result:Result:Result:Result:Result:Result:Result:Result:Result:
I just don't know why I can't parse only numbers, there is probably something that machine sends and it isn't parsed by m = m.replaceAll("[^\\d.]", "");
You're building your String incorrectly. It should be:
String message = new String(buffer, 0, bytesRead);
where 'bytesRead' is the count returned by the read() method. It's a byte count, not a char count.

How can I fix my code so it can input letters [duplicate]

This question already has answers here:
How to insist that a users input is an int?
(7 answers)
Closed 9 years ago.
So i'm just learning java and I know this issue is very stupid, this is from the book Head Frist Java. When I try to put a letter instead of a number it crashes, how do I fix that? If I want it to say "pleasse try again with a number" when letter is entered.
public class Game {
public static void main(String[] args)
{
int numOfGuesses = 0;
GameHelper helper = new GameHelper();
SimpleDotCom theDotCom = new SimpleDotCom();
int randomNum = (int) (Math.random() * 5);
int[] locations = {randomNum, randomNum+1, randomNum+2};
theDotCom.setLocationCells(locations);
boolean isAlive = true;
while (isAlive == true)
{
String guess = helper.getUserInput("enter a number");
String result = theDotCom.checkYourself(guess);
numOfGuesses++;
if (result.equals("kill")) {
isAlive = false;
System.out.println("You took " + numOfGuesses + " guesses");
}
}
}
}
public class GameHelper {
private static final String alphabet = "abcdefg";
private int gridLength = 7;
private int gridSize = 49;
private int [] grid = new int[gridSize];
private int comCount = 0;
public String getUserInput(String prompt) {
String inputLine = null;
System.out.print(prompt + " ");
try {
BufferedReader is = new BufferedReader(
new InputStreamReader(System.in));
inputLine = is.readLine();
if (inputLine.length() == 0 ) return null;
} catch (IOException e) {
System.out.println("IOException: " + e);
}
return inputLine.toLowerCase();
}
public class SimpleDotCom {
int[] locationCells;
int numOfHits = 0;
public void setLocationCells(int[] locs)
{
locationCells = locs;
}
public String checkYourself(String stringGuess) {
int guess = Integer.parseInt(stringGuess);
String result = "miss";
for (int cell: locationCells)
{
if (guess == cell) {
result = "hit";
numOfHits++;
break;
}
}
if (numOfHits == locationCells.length)
{
result = "kill";
}
System.out.println(result);
return result;
}
In the following -
int guess = Integer.parseInt(stringGuess);
the parsing succeeds only if stringGuess contains some integer (within the range of [-2147483648 - 2147483647]. Otherwise, it fails with an exception.
To avoid that you have to make sure that stringGuess contains the right value.
Following is where the value comes from -
String guess = helper.getUserInput("enter a number");
String result = theDotCom.checkYourself(guess);
It's the getUserInput() method -
public String getUserInput(String prompt) {
String inputLine = null;
System.out.print(prompt + " ");
try {
BufferedReader is = new BufferedReader(new InputStreamReader(System.in));
inputLine = is.readLine();
if (inputLine.length() == 0)
return null; // this cannot be parsed
} catch (IOException e) {
System.out.println("IOException: " + e);
}
return inputLine.toLowerCase(); //this might not be an integer
}
And that's the part that you need to fix.
Following should do the job -
//...
BufferedReader is = new BufferedReader(new InputStreamReader(System.in));
while (true) { //keep reading
try {
inputLine = is.readLine();
int num = Integer.parseInt(inputLine); //make sure it's an integer
if(num > -1 && num < 10) { // if it is, and within [0-9]
break; // stop reading
}
} catch (Exception e) { // if not prompt again
System.out.println("pleasse try again with a number within [0-9]");
}
}
return inputLine; // no to lower case, it's a number
You can still better it up, by say just returning an int form this method, instead of String.
If you don't know if stringGuess is an integer or not, you can put Integer.parseInt(stringGuess) in a try { } catch construct. parseInt throws an exception if its input cannot be turned into an integer, so catch it. In the catch block, we know that it was not an integer. Otherwise it was an integer. Now do the logic you want to do (displaying a message, choosing to loop or not, etc)
(If you have not yet done exception handling, look up try and catch in Java)
as suggested by #patashu you can use try{ } catch() { }
as Integer.parseInt(argument) throws NumberFormatException if the argument is not a number(number in the form of string).
and about calling your input function again if user enters letter then you can simply do it by giving that particular input method a call inside catch block like:
try{
int guess = Integer.parseInt(stringGuess);
-----
-----
}
catch(NumberFormatException e){
System.out.println("Oooppps letter entered - try again with number ");
/**
now here make call to your method that takes input i.e getUserInput() in your case
**/
}

Categories

Resources