Java gui, Client issue when trying to convert into gui - java

I have made a Client/Server programme in java, I have gotten it to work using the cmd perfectly as i want, now i am trying to convert the client side of the code into GUI, however i am having trouble with printing the client msg and reading the client input from the text fields and the server msg, here is what I have done so far, i get no errors when compiling but the gui it self doesn't run, any help is appreciated.
Here is the Client code:
import java.net.*;
import java.io.*;
import java.awt.*;
import java.util.Scanner;
import javax.swing.*;
public class TcpClient
{
public static void main(String[] args)
{
try
{
new TcpClient().start();
}
catch(Exception e)
{
System.out.println("Major Error" + e.getMessage());
e.printStackTrace();
}
}
public void start() throws IOException
{
JFrame build = new JFrame("Client");
JTextField serv = new JTextField();
JTextField clie = new JTextField();
build.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
serv.setBounds(50,210,300,50);
build.add(serv);
clie.setBounds(350,210,300,50);
build.add(clie);
//=====================================================================
Socket clientSocket = null;
InetAddress hostA = null;
PrintWriter clientOutput = null;
BufferedReader clientInput = null;
BufferedReader standardInput = null;
try
{
hostA = InetAddress.getLocalHost();
clientSocket = new Socket(hostA.getHostName(), 5600);
clientInput = new BufferedReader(new InputStreamReader(clientSocket.getInputStream()));
clientOutput = new PrintWriter(clientSocket.getOutputStream(), true);
standardInput = new BufferedReader(new InputStreamReader(System.in));
String serverMsg, clientMsg;
//read from a socket and respond back to server
while((serverMsg = clientInput.readLine()) != null)
{
serv.setText("Server Saying - " + serverMsg);
if(serverMsg.equals("exit"))
break;
clientMsg = standardInput.readLine();
if(clientMsg != null)
{
clie.setText("Client Saying - " + clientMsg);
clientOutput.println(clientMsg);
}
}
}
catch(UnknownHostException e)
{
System.exit(1);
}
catch(IOException e)
{
System.exit(1);
}
finally
{
//clean up time
clientOutput.close();
clientInput.close();
standardInput.close();
clientSocket.close();
}
//=====================================================================
build.setLayout(null);
build.setSize(700,600);
build.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
build.setVisible(true);
build.setResizable(false);
}
}

As mentioned in the comments you should study multithreading and especially the EDT
What is happening right now is that your code and your GUI and preventing each other from working properly. By having your GUI run on the EDT your application can run without holding back the GUI. When the application has changes to report that are relevant for your GUI you can just inform the EDT when the time comes.

Related

server client chatroom program in java shows Address already in use

I am new to networking and I am trying to write the server client program. Still, I keep getting Address already in use and cant chat. A friend of mine run this in his pc and it was working. Can somebody explain to me why I keep getting this error?
Here is the server class:
import java.net.*;
import java.io.*;
class server
{
public static void main(String []args)
{
try
{
ServerSocket serv = new ServerSocket(8001);
System.out.println("Server up and listening:");
Socket S = serv.accept();
InetAddress obj = S.getInetAddress();
System.out.println("Request coming from:");
BufferedReader br = new BufferedReader(new InputStreamReader(S.getInputStream()));
String msg = br.readLine();
System.out.println("Message recieved:"+msg);
br.close();
serv.close();
}
catch(Exception e)
{
System.out.println(e.getMessage());
}
}}
Here is the client class:
import java.net.*;
import java.io.*;
import java.util.*;
class client`{
public static void main(String [] args)
{
Socket s = null;
BufferedOutputStream bout = null;
InetAddress obj = null;
try {
obj = InetAddress.getByName(args[0]);
s = new Socket(obj, 8001);
String str = new Scanner(System.in).nextLine();
byte[] arr = str.getBytes();
bout = new BufferedOutputStream(s.getOutputStream());
bout.write(arr);
bout.flush();
bout.close();
s.close();
}
catch(Exception e)
{
System.out.println(e.getMessage());
}
} }
I appreciate any help you can provide!
use below command to determine if you have any open port on the machine where you are running your Server program
netstat -nao | find "8001"
You can simply change 8001 to another value. It looks like that it is under use by another program. Depends on your operating system, there are plenty ways to learn which ports are occupied.

Server is not sending back an acknowledgment to Client

I have my server code below over here:
public void startServer() {
ServerSocket listener = selectUnusedPortFromRange(1024, 65535);
Thread t = new Thread(new Runnable() {
#Override
public void run() {
try {
String command = null;
while (true) {
Socket socket = listener.accept();
System.out.println("Got a connection from: " + socket.getLocalPort());
BufferedReader in = new BufferedReader(new InputStreamReader(socket.getInputStream()));
command = in.readLine();
System.out.println("GOT HERE"); //Not being printed out
if (command != null && !"".equals(command)) {
if ("connection".equals(command)) {
Writer writer = new BufferedWriter(new OutputStreamWriter(socket.getOutputStream()));
writer.write("success\n");
writer.flush();
}
}
}
}
}
}
t.start();
}
This is my client side:
public void makeConnection() {
try {
Socket socket = new Socket(IP, PORT);
Writer writer = new PrintWriter(socket.getOutputStream(), true);
writer.write("connection\n");
BufferedReader socketRead = new BufferedReader(new InputStreamReader(socket.getInputStream()));
String str;
while ((str = socketRead.readLine()) != null) {
if ("success".equals(str)) {
System.out.println("Successfully saved all hosts to: " + listOfHosts.get(i));
socketRead.close();
socket.close();
iStream.close();
writer.close();
}
}
}catch (Exception e) {
System.out.println(e.getMessage());
}
}
On the client side after I create my socket to the connect to the server I write "connection" into the outputStream of the socket and wait for an acknowledgement back from the server saying success. For some reason the connection is not being made to the server. In the server System.out.println("Got a connection from: " + socket.getLocalPort()); this line is not being printed out.
Is there something wrong that I am doing. I can't spot it. And I am not getting an exception thrown when I try to connect to my server.
1) Make sure you use the same port for both the Client and Server. They must communicate over the same port. It seems you may be using different ports currently.
2) Make sure you actually start your server thread. As-is in your code above, you make a new Thread, but never start it. t.start() must be called somewhere.
3) If this is on your local machine, you may be better off using localhost instead of the actual IP address. Firewalls might treat your external IP differently.
4) Terminate your messages with a newline character, such as \n, so that your BufferedReader can use it's readLine() method. For good measure, also follow-up by flushing the writer's buffer, just in case the newline character didn't trigger that. writer.flush();
And lastly, make sure you terminate the JVM before trying to run your code again. Your code has not shutdown mechanism to un-bind the server from the port... so you may get an exception thrown telling you the port and/or address are already in use. If that happens, either change ports, or kill the java process running in the background.
Here is your code, slightly modified to run on my system. It's working as you might expect it to. I tried to change as little as possible just to get it working on my system. One note is, I hard-coded the port number into the server and client - that's not required, it was just convenient for me to test with:
import java.io.BufferedReader;
import java.io.BufferedWriter;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.OutputStreamWriter;
import java.io.PrintWriter;
import java.io.Writer;
import java.net.ServerSocket;
import java.net.Socket;
public class Test {
public static void main(String[] args) throws IOException {
Test test = new Test();
test.startServer();
test.makeConnection();
}
public void startServer() throws IOException {
final ServerSocket listener = new ServerSocket(60001);
Thread t = new Thread(new Runnable() {
#Override
public void run() {
try {
String command = null;
while (true) {
Socket socket = listener.accept();
System.out.println("Got a connection from: " + socket.getLocalPort());
BufferedReader in = new BufferedReader(new InputStreamReader(socket.getInputStream()));
command = in.readLine();
System.out.println("GOT HERE");
if (command != null && !"".equals(command)) {
if ("connection".equals(command)) {
Writer writer = new BufferedWriter(new OutputStreamWriter(socket.getOutputStream()));
writer.write("success\n");
writer.flush();
}
}
}
} catch (Exception e) {
e.printStackTrace();
}
}
});
t.start();
}
public void makeConnection() {
System.out.println("Making Connection");;
try {
Socket socket = new Socket("localhost", 60001);
Writer writer = new PrintWriter(socket.getOutputStream(), true);
writer.write("connection\n");
writer.flush();
BufferedReader socketRead = new BufferedReader(new InputStreamReader(socket.getInputStream()));
String str;
while ((str = socketRead.readLine()) != null) {
if ("success".equals(str)) {
System.out.println("Successfully saved all hosts to: "); //+ listOfHosts.get(i));
socketRead.close();
socket.close();
//iStream.close();
writer.close();
}
}
}catch (Exception e) {
System.out.println(e.getMessage());
}
}
}
I was facing the exact same issue. I overcame it by using an ACK mechanism (Wasn't my idea, it was suggested to me). The idea is that client would make a request to server and keep the socket connection alive (and the ouput stream open) till server responds back an agreed ACK message over the same channel. Once the client receives the ACK message, only then it would close the connection.
Below is the code for Server :-
final ServerSocket listener = new ServerSocket(11111);
Thread t = new Thread(new Runnable() {
#Override
public void run() {
try {
String command = null;
while (true) {
System.out.println("About to accept");
Socket socket = listener.accept();
System.out.println("Got a connection from: " + socket.getLocalPort());
DataInputStream inputStream = new DataInputStream(socket.getInputStream());
StringBuilder str = new StringBuilder(inputStream.readUTF());
//command = in.readLine();
System.out.println("GOT HERE. Msg received : "+str);
if (str != null && !"".equals(str.toString())) {
command = str.toString();
if ("connection".equals(command)) {
System.out.println("Got connection message");
DataOutputStream outputStream = new DataOutputStream(socket.getOutputStream());
outputStream.writeUTF("connection");
outputStream.close();
}
}
inputStream.close();
System.out.println("Done");
}
} catch (IOException e) {
e.printStackTrace();
} finally {
}
}
});
t.start();
}
Client :-
public void makeConnection() {
try {
System.out.println("In makeConnection");
Socket socket = new Socket("127.0.0.1", 11111);
DataOutputStream outputStream = new DataOutputStream(socket.getOutputStream());
outputStream.writeUTF("connection");
InputStream inputStream = socket.getInputStream();
DataInputStream dataInputStream = new DataInputStream(inputStream);
StringBuilder str;
do {
str = new StringBuilder(dataInputStream.readUTF());
} while (!str.toString().equals("connection"));
System.out.println("Successfully saved all hosts to: ");
outputStream.close();
dataInputStream.close();
socket.close();
outputStream.close();
}catch (Exception e) {
System.out.println(e.getMessage());
}
}
A call to start the proceedings :-
public void start() throws IOException, InterruptedException {
System.out.println("Starting server");
startServer();
Thread.sleep(1000);
System.out.println("Starting connection");
makeConnection();
}

Java Server, Unity C# Client Are Freezing

I am building a Sphinx4 Java Server where Unity3D should communicate with. Sending audio data from Unity C# to the Java server works fine. Speech recognition with the received data works fine too. The problem appears when I try to send data from Java back to C#.
My current code:
JAVA
package main;
import java.io.InputStream;
import java.io.PrintWriter;
import java.net.ServerSocket;
import java.net.Socket;
import edu.cmu.sphinx.api.Configuration;
import edu.cmu.sphinx.api.SpeechResult;
import edu.cmu.sphinx.api.StreamSpeechRecognizer;
public class SpeechRecognition {
private static StreamSpeechRecognizer recognizer;
private static Configuration configuration;
public static void main(String[] args) {
configuration = new Configuration();
configuration.setAcousticModelPath("resource:/edu/cmu/sphinx/models/en-us/en-us");
configuration.setDictionaryPath("resource:/edu/cmu/sphinx/models/en-us/cmudict-en-us.dict");
configuration.setLanguageModelPath("resource:/edu/cmu/sphinx/models/en-us/en-us.lm.bin");
try {
recognizer = new StreamSpeechRecognizer(configuration);
ServerSocket serverSocket = new ServerSocket(82);
while (System.in.available() == 0) {
Socket socket = serverSocket.accept();
System.out.println("Client found");
String recognized = RecognizeText(socket.getInputStream());
System.out.println("sending now");
PrintWriter out = new PrintWriter(socket.getOutputStream(), true);
String json = recognized;
out.print(json);
out.flush();
out.close();
socket.close();
}
} catch (Exception e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
System.out.println("Quitting...");
serverSocket.close();
}
private static String RecognizeText(InputStream stream) throws Exception {
recognizer.startRecognition(stream);
SpeechResult result;
String resultString="";
while ((result = recognizer.getResult()) != null) {
resultString = result.getHypothesis();
System.out.format("Hypothesis: %s\n", resultString);
}
recognizer.stopRecognition();
return resultString;
}
}
Now my C# code is like this:
void Start () {
dataPath = Application.dataPath;
t = new Thread(Client);
t.Start();
}
private void Client()
{
String input;
TcpClient tcpClient = new TcpClient("localhost", 82);
NetworkStream networkStream = tcpClient.GetStream();
BinaryWriter bw = new BinaryWriter(networkStream);
var filepath = dataPath + "/Resources/audio/test.wav";
FileStream filestream = new FileStream(filepath, FileMode.Open, FileAccess.Read);
BinaryReader filereader = new BinaryReader(filestream);
byte[] bytes = filereader.ReadBytes((Int32)filestream.Length);
bw.Write(bytes);
bw.Flush();
StreamReader streamReader = new StreamReader(networkStream);
input = streamReader.ReadToEnd();
print("Received data: " + input + "\n");
}
The recognition takes around 10 seconds. When te result is given the system freezes.
The Println("sending now") (in Java) is not printed. So it freezes before it even reaches it.
The weird thing is: When I only send text from Java to C# or from C# to Java, it works. If I want to send and receive on both ends, it freezes. And I need to send and receive data at the same time
I have found the anwser:
The loop is not broken in RecognizeText, placing the return statement within the while loop fixes the issue, as the recognized text will be returned first anyway.

Application Hangs over the socket, Unable to read client data at server side

I am trying to implement a client server socket connection where i am passing commands like ls/pwd over the GUI and I use an url(localhost) to establish the server connection at the port. Although i am able to establish a connection with client ,the code does not proceed beyond the Client Connection accepted state. I.e. it does not read the input at the server end which was sent by the client over the socket. Below are my three classes, Mainserver, ClientHandler(this handles the thread connections for the server)and the Client.
This is the Client Action button performed code:
private void jButton1ActionPerformed(java.awt.event.ActionEventevt) {
command = jTextField1.getText();
String url = jTextField3.getText();
try {
System.out.println("Before socket connection");
Socket socket = new Socket(url, 9002);
System.out.println("After socket connection");
PrintWriter out = new PrintWriter(socket.getOutputStream(), true);
BufferedReader in = new BufferedReader(new InputStreamReader(socket.getInputStream()));
System.out.println("After Buffered readers");
System.out.println("After getting streams");
if (socket != null) {
try {
int x = Integer.parseInt(command);
flag = 1;
} catch (Exception e) {
flag = 0;
}
if (flag == 0) {
String[] cmd = {"/bin/sh", "-c", command};
System.out.println("the value of command in GUI class is " + Arrays.toString(cmd));
try {
String commd = Arrays.toString(cmd);
System.out.println(commd);
out.write(commd);
input = in.readLine();
}
catch (IOException ex1)
{
Logger.getLogger(TestGUI.class.getName()).log(Level.SEVERE, null, ex1);
}
jTextField2.setText(input.toString());
}
}
}//try end of the first one
catch (IOException ex) {
Logger.getLogger(TestGUI.class.getName()).log(Level.SEVERE, null, ex);
}
The server class:
public class ServerMain {
public static void main(String[] args) throws IOException, InterruptedException {
int number, temp;
try {
ServerSocket serverSocket = new ServerSocket(9002);
System.out.println("server has been started in the server");
System.out.println("Server is waiting connection at" + InetAddress.getLocalHost().getCanonicalHostName() + "port" + serverSocket.getLocalPort());
while (true) {
Socket socket = serverSocket.accept();
System.out.println("Client Connection Accepted");
//pass on handling on this client to a thread
(new ClientHandler(socket)).start();
}
} catch (Exception e) {
System.err.println("Server already in use");
System.exit(-1);
}
}
}
The client Handler for the Server:
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.PrintWriter;
import java.net.ServerSocket;
import java.net.Socket;
import java.util.logging.Level;
import java.util.logging.Logger;
/*
* To change this license header, choose License Headers in Project Properties.
* To change this template file, choose Tools | Templates
* and open the template in the editor.
*/
/**
*
* #author ameerah
*/
public class ClientHandler extends Thread {
private static int BUFSIZE = 1024;
private StringBuffer result;
ServerSocket serverSocket;
String serverText;
StringBuffer output = new StringBuffer();
private Object serversocket;
public Socket getSock() {
return sock;
}
public void setSock(Socket sock) {
this.sock = sock;
}
Socket sock;
public ClientHandler(Socket sock) {
this.sock = sock;
}
#Override
public void run() {
PrintWriter outWriter = null;
try {
BufferedReader myInput = new BufferedReader(new InputStreamReader(sock.getInputStream()));
outWriter = new PrintWriter(sock.getOutputStream());
System.out.println(
"before accepting the command in server");
String inputLine;
while ((inputLine = myInput.readLine()) != null) //String command = myInput.readLine();
{
System.out.println(inputLine);
String result = "";
try {
result = executeCommand(inputLine);
} catch (IOException ex) {
Logger.getLogger(ClientHandler.class.getName()).log(Level.SEVERE, null, ex);
} catch (InterruptedException ex) {
Logger.getLogger(ClientHandler.class.getName()).log(Level.SEVERE, null, ex);
}
System.out.println(result);
outWriter.write(result);
}
} catch (IOException ex) {
Logger.getLogger(ClientHandler.class.getName()).log(Level.SEVERE, null, ex);
} finally {
outWriter.close();
}
}
public String executeCommand(String cmd)
throws IOException, InterruptedException {
try {
Process p = Runtime.getRuntime().exec(cmd);
p.waitFor();
BufferedReader reader
= new BufferedReader(new InputStreamReader(p.getInputStream()));
System.out.println("Inside the execute method");
String line = "";
while ((line = reader.readLine()) != null) {
output.append(line + "\n");
}
} catch (Exception e) {
e.printStackTrace();
}
return output.toString();
}
}
I have been at it for some time, and tried using different streams such as ObjectInputStream, ObjectOutputStream, but the code hangs each time. I cannot see at this point where Im going wrong :( I've searched in several forums but I do not still get an idea where Im going wrong here.Would appreciate any help.!
Best Regards
It was the readLine() which was expecting '\n' at the end. Therefore once i appended '\n' at the end and added out.flush() it was able to read and not keep hanging waiting for more inputs, and now the application is working.
Thank you very much for your helpful suggestions. The out.flush() advice proved to be very helpful.
Few tips to isolate the problem.
Check the value of command and catch Exception stack trace.
After out.write(commd); : add one more line out.flush(); After flush, server will get the data from client. Same is the case with outWriter. flush() should be called on outWriter after writing the data.
You are looking for an end of line to end your input loop but you are using write.
Change your send data statements to use println.
Client:
out.println(commd);
Server:
outWriter.println(result);

Swing Socket Testing

I am trying a program with Swing.
I am using a socket to connect to the server, and the client has the gui code.
public class FactClient extends JFrame implements ActionListener
{
Socket s;
InputStream in;
OutputStream os;
Scanner sin;
PrintWriter out;
JPanel jp;
JTextField jt;
JButton jb;
JLabel jl;
FactClient()
{
jp = new JPanel();
jt = new JTextField("Enter number",15);
jb = new JButton("Compute Factorial");
jl = new JLabel("Answer");
jb.addActionListener(this);
jp.add(jt);
jp.add(jb);
jp.add(jl);
add(jp);
setVisible(true);
setSize(200,100);
try
{
s = new Socket("localhost",8189);
try
{
in = s.getInputStream();
os = s.getOutputStream();
sin = new Scanner(in);
out = new PrintWriter(os);
out.println("Done with the bingo");
}
finally {}
}
catch(Exception e)
{
System.out.println("Error in client code " + e );
}
}
public void actionPerformed(ActionEvent ae)
{
try {
System.out.println("Connection established " + jt.getText());
String t = jt.getText();
out.println("Ashish");
System.out.println("Data Send");
t = sin.nextLine();
jl.setText(t);
}
catch(Exception e)
{
System.out.println("Error in client code " + e );
}
}
public static void main(String args[])
{
new FactClient();
}
}
import java.io.*;
import java.util.*;
import java.net.*;
public class FactServer
{
public static void main(String args[])
{
ServerSocket s;
Socket socket;
try
{
s= new ServerSocket(8189);
socket = s.accept();
try
{
InputStream in = socket.getInputStream();
OutputStream os = socket.getOutputStream();
// Scanner sin = new Scanner(in);
BufferedReader br = new BufferedReader(new InputStreamReader(in));
PrintWriter ou = new PrintWriter(os);
System.out.println("Connection Established : Stream initailzed");
try
{
String data = br.readLine();
System.out.println("Data Recvd." + data);
data = br.readLine();
}
catch(Exception e)
{
System.out.println("EEEEEEEEEEEEE" + e);
}
//int fact = data +20;
ou.println("40");
}
catch (Exception e)
{
System.out.println("ERROR :P");
}
finally
{
socket.close();
}
}
catch(Exception e)
{
System.out.println("ERROR" + e);
}
}
}
The server code simply reads the data that I send using System.out.println. But the problem is it hangs up; the server never gets the data!
out.println("Done with the bingo");
This is the first string that server should get. But it stays in the wait state as if nothing is received.
You must use flush() after each println() or activate automatic flushing on the PrintWriter so the data gets really sent:
...
out = new PrintWriter(os);
out.println("Done with the bingo");
out.flush();
...
or
...
out = new PrintWriter(os, true); // autoflush
out.println("Done with the bingo");
...
don't forget the server...
Enabling autoflush in your PrintWriter as Carlos said should solve your main question. A couple of other thoughts you might consider:
Wrap the server logic in a loop (e.g. while(true) {...}) if you want it to handle multiple client requests, and handle each request in a separate thread.
Since you are making the client request on the Swing Event Dispatch Thread (i.e. the actionPerformed() method) you might consider wrapping it in a Runnable or SwingWorker so you don't block the dispatch thread. Otherwise you might notice the UI appear to hang or not paint while the socket communication is happening.

Categories