SOLVED = my server code need to place in the right place. Outside EventQueue.Invokeletter{});
When I run the client and click button login, the client cannot connect to server.
The first time I use it, it's working, but for no reason my Client cannot connect to Server.
What should I do to make it right?
Server Code
public static void main(String args[]) {
java.awt.EventQueue.invokeLater(new Runnable() {
public void run() {
try {
new mainmenu().setVisible(true);
ServerSocket ss=new ServerSocket(1234);
Socket socket1=ss.accept();
} catch (IOException ex) {
Logger.getLogger(mainmenu.class.getName()).log(Level.SEVERE, null, ex);
}
}
});
}
Client Code
private void btnLoginActionPerformed(java.awt.event.ActionEvent evt) {
try {
Socket cs = new Socket("localhost", 1234);
} catch (IOException ex) {
Logger.getLogger(mainclient.class.getName()).log(Level.SEVERE, null, ex);
}
}
Here:
ServerSocket ss=new ServerSocket(1234);
Socket socket1=ss.accept();
That waits for one client to connect. Then your run() method deals with that client ... and ends!
If you want your code to wait again, you need to put a loop around that part of your code.
In other words: you wrote code that will open a server socket, wait for an incoming connection, handle that, and then ... fade away. If you want to serve more than one client over time, that "fade away" part needs to be replaced with a loop that keeps waiting for new clients, as long as the "server" program is up and running.
Related
I have to implement (in the server side) the quit command which disconnects any clients still connected and closes the server.
Here the server code.
public class Server {
public static void main (String args []) {
if (args.length < 1) {
System.err.println("Usage: java Server <port>");
return;
}
int port = Integer.parseInt(args[0]);
try {
ServerSocket listener = new ServerSocket(port);
Files input = new Files();
while (true) {
System.out.println("Listening...");
Socket s = listener.accept();
System.out.println("Connected");
Thread clientHandlerThread = new Thread(new ClientHandler(s,input));
clientHandlerThread.start();
}
} catch (IOException e) {
System.err.println("Error during I/O operation:");
e.printStackTrace();
}
}
}
how can the server accept command line instructions while it is running?
First of all, you have to keep track of all the clients that you create by putting their instances in a list so that when you're going to shutdown everything, you could access them and tell them to finish their job.
And about how to tell the thread instances to do that, you should call their interrup() method to inform them that they should finish/stop whatever it's doing. Calling the interrupt() method on a thread leads an InterruptedException in the thread that you should handle and gracefully finish whatever you're doing.
For example if you have something like this in the run method of your ClientHandler:
while (true) {
try {
Thread.sleep(interval);
} catch (InterruptedException e){
Thread.currentThread().interrupt();
System.out.println(
"We've been asked to finish up the communication. Bye! ;)");
}
// do your business
}
This was of course a very simplified scenario to demonstrate the overall approach. You should be able to find tons of tutorials online about how to use the interrupt.
Long story short, I stole and modified some code from GeeksForGeeks to practice with sockets. Running code modified for localhost works fine on desktop, but when modifying and attempting to host on Heroku, I can't seem get a connection between the server and client. Server appears to launch and run fine on Heroku, and logs connections that I'm not even making (no idea where those are coming from). Client on the other hand seems to connect, but then doesn't do anything when I send a message. Server doesn't even log my attempted connection, so I know it probably isn't even connecting.
Server code: https://github.com/RenegadeB5/socket in /src/main/java/
Client Code:
import java.io.*;
import java.net.*;
import java.util.Scanner;
public class Client
{
public static void main(String args[]) throws UnknownHostException, IOException
{
Scanner scn = new Scanner(System.in);
// establish the connection
Socket s = new Socket("<my app name>.herokuapp.com", 80);
// obtaining input and out streams
DataInputStream dis = new DataInputStream(s.getInputStream());
DataOutputStream dos = new DataOutputStream(s.getOutputStream());
// sendMessage thread
Thread sendMessage = new Thread(new Runnable()
{
#Override
public void run() {
while (true) {
// read the message to deliver.
String msg = scn.nextLine();
try {
// write on the output stream
dos.writeUTF(msg);
} catch (IOException e) {
e.printStackTrace();
}
}
}
});
// readMessage thread
Thread readMessage = new Thread(new Runnable()
{
#Override
public void run() {
while (true) {
try {
// read the message sent to this client
String msg = dis.readUTF();
System.out.println(msg);
} catch (IOException e) {
e.printStackTrace();
}
}
}
});
sendMessage.start();
readMessage.start();
}
}
I've tried so many different combinations and solutions, and can't find any examples of this being done before. I'd like to know what I'm doing wrong so that I can move on from this headache. Thanks in advance!
Java Socket and ServerSocket use TPC, which is not supported for free by Heroku. As a result, the server will run fine, but anything being sent via TCP, including connection attempts, will not make it to your server unless they are done via http.
I'm trying to get a threaded chatserver working. But my socket is closing and I have no clue why it is.
In the server class I create a new ClientHandler
addHandler(new ClientHandler(this, incoming));
addHandler starts the thread and adds the new ClientHandler to an ArrayList in server.
incoming is the client socket.
public ClientHandler(Server serverArg, Socket sockArg) {
server = serverArg;
client = sockArg;
System.out.println(client.isClosed());
}
There is nothing called between
public void run() {
try {
System.out.println(client.isClosed());
in = new Scanner(client.getInputStream());
out = new PrintWriter(client.getOutputStream(), true);
announce();
System.out.println("Waiting for input");
boolean done = false;
while(!done && in.hasNextLine()) {
System.out.println("There is input!");
server.broadcast(clientName + ": " + in.nextLine());
}
} catch (Exception e) {
System.out.println(e.toString());
}
}
When I run this code. This is the output:
false
true
java.net.SocketException: Socket is closed
Why is it closing immediately after creating this class / before starting it?
The connection is being closed by your code between when you add the handler and when the run() method is called. I suggest you add a breakpoint to the close method in the JDK and see where it is called. Or have a look at the code after you add the handler.
You can use a networking sniffer like wireshark or tcpdump.
To find out that if the connection broke due to the server side.
I guess that maybe the client side close the connection.
So, I have the following code that catches a new connection, then hands that connection to its own thread to handle the client.
private void loop(int port) {
// Opens a port for connections.
ServerSocket serverSocket = null;
try {
serverSocket = new ServerSocket(port);
System.out.println("Server running in port " + port);
} catch (IOException e1) {
// TODO Auto-generated catch block
e1.printStackTrace();
}
// Listens for a connection
while (onlineState == true && serverSocket != null) {
Socket clientSocket = new Socket();
try {
clientSocket = serverSocket.accept();
System.out.println(clientSocket.getInetAddress() + " has connected to the port " + clientSocket.getPort());
new Thread(new SocketThread(clientSocket)).run();
clientSocket.close();
} catch (IOException e) {
e.printStackTrace();
}
}
So, my problem here is that when I try to connect with multiple client apps to the server, the server only seems to either accept one connection at any given time. The client itself is a very simple application of the basic tutorial: it simply repeats any string that the server sends to it.
I have two guesses as to why this is happening: a) there's something wrong with my handling code, b) it's because both connections are from the same IP.
However, neither case is a good thing. Any ideas what I'm doing wrong? (Except everything)
Two things:
You want to call start(), not run() on your Thread object. The difference is that start() actually goes and does threaded stuff, like running it in the background. Calling run() from where you call it there will handle all the client communication right there, inline. That's why you only ever accept one connection - you won't accept any more until you've serviced that client.
You don't want to call clientSocket.close() in your main thread. In your implementation of SocketThread, call clientSocket.close() at the end of your run() method, probably inside a finally block.
Also, does SocketThread extend Thread? If so, you don't need new Thread(), just do
new SocketThread(clientSocket).start();
If it doesn't extend Thread, why not name it SocketRunnable or ClientRunnable or something like that.
Im working on a socket program in Java.
Im running a GUI with a socket server in the background.
The socket server is running a thread that checks for socket messages every 10ms.
Both of them runs fine together but as soon as I try to open my File dialog in the gui, the gui crashes, but the server keeps on running.
Im thinking that I run the server (or the server thread) in a wrong way.
The file dialog works fine if I skip the socket.
What could be the problem, could it be that Im running the thread in a wrong way?
(this in one class)
public ServerController(){
ServSocket st = new ServSocket();
Thread thread1=new Thread(st);
thread1.start();
}
(this is my thread)
public void run(){
while (true) {
try {
Thread.sleep(10);
}
catch (InterruptedException e) {}
switch (Status) {
case CONNECTED:
try {
socket = new Socket(hostIP, port);
System.out.println("Connected on: " + hostIP + port);
out = new PrintWriter(socket.getOutputStream(), true);
changeStatus(STARTSENDING, true);
}
catch (IOException e) {
System.out.println("disconnected");
}
break;
(and this is my main)
static ServerController scon;
static Controller cn;
public static void main(String[] args) {
scon = new ServerController();
cn = new Controller();
cn.gui();
}
Just guessing here, but I think it's relating to the EDT.
Are you trying to launch the dialog from outside the EDT? http://en.wikipedia.org/wiki/Event_dispatching_thread
If you think you might be, try using SwingUtilities static methods (specifically isEventDispatchThread and invokeLater) to hone in and rectify the issue:
http://java.sun.com/javase/6/docs/api/javax/swing/SwingUtilities.html#isEventDispatchThread()
http://java.sun.com/javase/6/docs/api/javax/swing/SwingUtilities.html#invokeLater(java.lang.Runnable)
hth
The problem is now solved.
Seems that the problem was that i had a scanner that was waiting for input(string = sc.next();) every 10ms in the thread, and after a few input my GUI showed.
I removed the Scanner and i now have a working application.