I'm trying to realize a simple client/server application in Java8.
I'm using this code:
`package prova;
import java.io.IOException;
import java.net.ServerSocket;
import java.net.Socket;
public class Main {
public static void main(String args[]){
ServerSocket ssock;
try {
System.out.println("Listening");
ssock = new ServerSocket(8080);
while(true){
Socket sock;
try {
sock = ssock.accept();
System.out.println("Connected");
new Thread(new Server(sock)).start();
}catch(IOException e1){e1.printStackTrace();}
}
}catch(IOException e2){e2.printStackTrace();}
}
}`
Server.java
package prova;
import java.io.IOException;
import java.io.PrintStream;
import java.net.Socket;
public class Server implements Runnable{
Socket clientSocket;
public Server(Socket cSocket){
this.clientSocket = cSocket;
}
public void run(){
try {
PrintStream pstream = new PrintStream
(clientSocket.getOutputStream());
for (int i = 100; i >= 0; i--) {
pstream.println(i +
" bottles of beer on the wall");
}
pstream.close();
clientSocket.close();
}
catch (IOException e) {
System.out.println(e);
}
}
}
When the application arrives to execute the instruction ssock.accept();
the application crashes. I really don't know what's the matter with this code. I've searched on internet but except for class server there is no difference between my code and a lot of solution/examples that i found. By the way since the application doesn't arrive to execute the thread I guess this is not related to my issue, maybe I'm wrong.
Thank you all in advance
that's the strange fact it doesn't provide any stacktrace. I'm running this code on win10 with eclipse mars 4.5.2. the code stops at this instruction sock = ssock.accept();
Yes, it's supposed to stop there -- it's waiting for a client program to connect on that same socket, server socket 8080, that's what accept() does, but you don't do that anywhere. The fix is simple -- have your client try to connect on the same socket that the server is waiting on.
Related
I am complete beginner and i have assignment to send something to server and get it back while using threads too.
My problem is that no matter which port I use, I get connection refused.
I think it might something to do with threads, but I am unsure what to do with them as it seems both start properly and client is the one throwing exception. I read somewhere that server should have some time to start connection so I put sleep but same thing again.
Main:
package advancedjavaassignment1;
public class MAIN {
public static void main(String[] args) {
SERVER.mainServer();
CLIENT.mainClient();
}
}
SERVER:
package advancedjavaassignment1;
import java.net.*;
import java.io.DataInputStream;
import java.io.DataOutputStream;
import java.io.IOException;
public class SERVER {
static void mainServer() {
serverTHREAD serverThread = new serverTHREAD();
serverThread.start();
try (
ServerSocket calcServer = new ServerSocket(10001); //Server created on port 2390
Socket inSocket = calcServer.accept(); //Server is listening
DataInputStream FromClient = new DataInputStream(inSocket.getInputStream());
DataOutputStream ToClient = new DataOutputStream(inSocket.getOutputStream());) {
int a = FromClient.readInt();
ToClient.writeInt(a);
}
catch (IOException e) {
System.out.println(e.getMessage()+ "Server");
}
}
}
}
CLIENT:
package advancedjavaassignment1;
import java.net.*;
import java.io.DataInputStream;
import java.io.DataOutputStream;
import java.io.IOException;
public class CLIENT {
static void mainClient() {
serverTHREAD clientThread = new serverTHREAD();
clientThread.start();
try {Thread.sleep(2000); System.out.println("break");} catch (InterruptedException ex) { }
try (Socket ClientSocket = new Socket("localhost",80);
DataInputStream FromServer = new DataInputStream(ClientSocket.getInputStream());
DataOutputStream ToServer = new DataOutputStream(ClientSocket.getOutputStream());) {
ToServer.writeInt(10);
int sum = FromServer.readInt();
System.out.println(sum);
ClientSocket.close();
}
catch(IOException exception)
{
System.out.println(exception.getMessage() + " - Client");
}
}
}
Looks like your server runs on port 10001 (although you wrote 2390 in the comment) and the client tries to connect to port 80. The client finds no server listening on that port, hence the connection refused error.
My apology, I forgot to change it, as I was experimenting with everything, this does not work even when ports are same.
I solved this by implementing Runnable. Worked immediately.
my name is Jędrzej and I am new here. I was trying to write a simple chat in java. I am trying to make multithread server so multiple clients can connect to this server. My client works fine, but if I run two clients, they dont see each others responses. Code bellow:`
package serverthread;
import java.io.IOException;
import java.net.ServerSocket;
import java.net.Socket;
public class ServerWIthThreads {
public static void main(String[] args){
try{
ServerSocket serverSocket = new ServerSocket(1234);
while(true){
Socket socket = serverSocket.accept();
Runnable r = new ThreadForServer(socket);
Thread t = new Thread(r);
t.start();
}
}catch(IOException e){
e.printStackTrace();
}
}
}
package serverthread;
import java.io.IOException;
import java.io.ObjectInputStream;
import java.io.ObjectOutputStream;
import java.net.Socket;
public class ThreadForServer implements Runnable{
private Socket socket;
private ObjectInputStream inputStream;
private ObjectOutputStream outputStream;
public ThreadForServer(Socket i){
socket = i;
}
#Override
public void run(){
try{
inputStream = new ObjectInputStream(socket.getInputStream());
outputStream = new ObjectOutputStream(socket.getOutputStream());
outputStream.flush();
while(true){
String message = (String) inputStream.readObject();
outputStream.writeObject(message);
outputStream.flush();
}
}catch(IOException e){
} catch (ClassNotFoundException e) {
e.printStackTrace();
}
}
}
`
The way you've implemented this, you're reading a message from one client and then writing it back to the same client.
You'll need to revise your program so that you can write the message to the Socket of the other connected client.
I tried to find something similar to help me with my code and I also tried to do it by myself but I got stuck on the end and I would really appreciate if someone would help me with that.
So I have already working simple Java Client/Server code and what i want to do is to upgrade it so it can work both ways, right now after launching the server and connecting to it by the client everything what u write as a client will be shown on the server too and i want to upgrade it so what i write on the client will be shown on the server and what i write on the server will be shown on the client.
myServer.java
import java.io.*;
import java.net.*;
public class myServer {
public static void main (String[] args) {
try {
int i=0;
ServerSocket ss = new ServerSocket(9000);
System.out.println("Listening...");
Socket s = ss.accept();
System.out.println("Connection accepted");
InputStream d1 = s.getInputStream();
while ((char)i !='q')
{
i = d1.read();
System.out.print((char)i);
}
s.close();
ss.close();
} catch (Exception e) {System.out.println("Error"); }
}
}
myClient.java
import java.io.*;
import java.net.*;
public class myClient {
public static void main(String[] args) {
try {
int i=0;
Socket s=new Socket("localhost",9000);
OutputStream o = s.getOutputStream();
while ((char)i !='q')
{
i = System.in.read();
o.write((char)i);
}
s.close();
} catch(Exception e) {System.out.println("Error"); }
}
}
Thank You in advance.
This is a problem I never figured out. I've asked many people, and they don't even know. Anyways, lets get to the problem. Here's what I tried to do... Create a client and a server. The client connects to the server, and sends a message to it every 3 minutes (I reduced the time for testing). There has to be two independent threads however (one for the client and server). What I found was, the client would continue to send messages, but the server would no longer listen on port 1234.
Client:
import java.io.PrintWriter;
import java.net.Socket;
public class Client {
public Client(){
startClient();
}
public void startClient(){
new Thread(new Runnable(){
#Override
public synchronized void run(){
try{
Socket sendChat = new Socket("localhost", 1234);
PrintWriter writer = new PrintWriter(sendChat.getOutputStream());
while(true){
Thread.sleep(1000); // normally 180000
writer.println("Hello Server!");
}
}catch(Exception err){
err.printStackTrace();
}
}
}).start();
}
}
Server:
import java.io.BufferedReader;
import java.io.InputStreamReader;
import java.net.ServerSocket;
import java.net.Socket;
import java.util.Date;
public class Server {
public Server(){
startServer();
}
public void startServer(){
new Thread(new Runnable(){
#Override
public synchronized void run(){
try{
#SuppressWarnings("resource")
ServerSocket server = new ServerSocket(1234);
while(true){
final Socket test = server.accept();
BufferedReader reader = new BufferedReader(new InputStreamReader(test.getInputStream()));
while(!test.isClosed()) {
Date date = new Date();
System.out.println("Server got message from client " + date);
}
reader.close();
}
}catch(Exception err){
err.printStackTrace();
}
}
}).start();
}
}
Start:
public class Start {
public static void main(String[] args){
new Server();
new Client();
}
}
I would greatly appreciate it if someone could tell me what is wrong, because I honestly have no clue.
Write below two lines out of while loop in Server class and it will work for you.
final Socket test = server.accept();
BufferedReader reader = new BufferedReader(new InputStreamReader(test.getInputStream()));
What is happening in your code : Server will wait for new client every time after completion of the while loop but there is no client which is going to connected with server at that instance. So server will wait untill a new client will come and server will accept that new client and continue its processing.
you are stack in a loop, try close the connection in the client after the message.
See these links they use
socket.setKeepAlive(true);
java.net.Socket TCP keep-alive usage
and
Permanent and persistent Socket connection in java
I'm trying to code a server-client communicating application which uses two separate threads, one for input and one for output. I'm having a weird "deadlock" issue, though: when one thread reads input, but the client hasn't sent anything, the thread stops (since it's waiting for input). However, for some reason, while the input thread is blocked, the output thread can't write anything.
This is illustrated in this code sample:
import java.io.*;
import java.net.*;
import java.nio.*;
import java.nio.channels.*;
public class TestServer {
public static void main(String... args) throws IOException {
/* Creates a server socket that lurks about our port waiting for connections */
ServerSocketChannel serverChannel = ServerSocketChannel.open();
serverChannel.configureBlocking(false);
serverChannel.socket().bind(new InetSocketAddress(4114));
while(true){
SocketChannel connectionChannel = serverChannel.accept();
if(connectionChannel != null){
final Socket connection = connectionChannel.socket();
new Thread(){
public void run(){
try {
System.out.println("READING");
System.out.flush();
// If the next line is commented out, nothing blocks
connection.getInputStream().read();
System.out.println("DONE READING");
System.out.flush();
} catch (Exception e){
e.printStackTrace();
}
}
}.start();
new Thread(){
public void run(){
try {
System.out.println("WRITING");
System.out.flush();
new DataOutputStream(connection.getOutputStream()).writeBytes("AUGH!!!");
//connection.getOutputStream().write(5);
System.out.println("DONE WRITING");
System.out.flush();
} catch (Exception e){
e.printStackTrace();
}
}
}.start();
break;
}
}
}
}
And the client code:
import java.net.*;
import java.io.*;
public class TestClient {
public static void main(String... args) throws IOException {
Socket connection = new Socket("127.0.0.1", 4114);
while(true){
System.out.println(connection.getInputStream().read());
}
}
}
The code sample above blocks, but if the line in the server is commented out it doesn't. Why is that? Is a socket limited to only waiting for input/output at the same time? What's going on?
I'm not sure why you are seeing this, but it has something to do with using channels.
If you replace this code with
ServerSocket ss = new ServerSocket(4114);
Socket connection = ss.accept();
it will work as you want.