I have a problem with this piece of code but I'm not able to see where is the error.
import java.io.*;
import java.net.*;
import java.util.concurrent.*;
public class Server {
public void startServer() {
final ExecutorService clientProcessingPool = Executors.newFixedThreadPool(10);
Runnable serverTask = new Runnable() {
#Override
public void run() {
try {
#SuppressWarnings("resource")
ServerSocket serverSocket = new ServerSocket(8080);
while (true) {
Socket clientSocket = serverSocket.accept();
clientProcessingPool.submit(new ClientTask(clientSocket));
}
} catch (IOException e) {
e.printStackTrace();
}
}
};
Thread serverThread = new Thread(serverTask);
serverThread.start();
}
private class ClientTask implements Runnable {
private Socket clientSocket;
private ClientTask(Socket clientSocket) {
this.clientSocket = clientSocket;
}
#Override
public void run() {
try {
// Read request
InputStream incommingIS = clientSocket.getInputStream();
byte[] b = new byte[8196];
int len = incommingIS.read(b);
if (len > 0) {
System.out.println("REQUEST"
+ System.getProperty("line.separator") + "-------");
System.out.println(new String(b, 0, len));
// Write request
Socket socket = new Socket("localhost", 8080);
OutputStream outgoingOS = socket.getOutputStream();
outgoingOS.write(b, 0, len);
// Copy response
OutputStream incommingOS = clientSocket.getOutputStream();
InputStream outgoingIS = socket.getInputStream();
for (int length; (length = outgoingIS.read(b)) != -1;) {
incommingOS.write(b, 0, length);
}
incommingOS.close();
outgoingIS.close();
outgoingOS.close();
incommingIS.close();
socket.close();
} else {
incommingIS.close();
}
} catch (IOException e) {
e.printStackTrace();
} finally {
try {
clientSocket.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
}
}
This code tries to simulate a HTTP proxy using sockets, the code receives the URL, process it and get back again to the browser untouched.
The problem is that the browser hangs, nothing is returned...
Any help would be much appreciated.
This is not a correct way to write a proxy. An HTTP proxy receives a CONNECT command, which tells it to connect to an upstream target. So the first thing you have to do is read one line, do the upstream connect, and return an appropriate status. If the status was OK, you then have to start two threads to copy bytes between upstream and downstream, one in each direction, closing both sockets when you have received EOS from both of them.
Related
my java socket server cannot accept more than one data at the same time in one client
Thread t1 = new Thread(() -> {
ServerSocket ss = null;
try {
ss = new ServerSocket(9000);
} catch (IOException e) {
e.printStackTrace();
}
try {
while(true) {
System.out.println("Waiting Transaction ..");
Socket clientSocket = ss.accept();
InetAddress inet = clientSocket.getInetAddress();
try{
while (clientSocket.getInputStream().available() == 0) {
Thread.sleep(100L);
}
byte[] data;
int bytes;
data = new byte[clientSocket.getInputStream().available()];
bytes = clientSocket.getInputStream().read(data,0,data.length);
String dataDB = new String(data, 0, bytes, "UTF-8");
System.out.println("received data\n time : "+ new Date() +"length data : " + dataDB.length());
System.out.println(dataDB);
String dataFrom = getFromServer(dataDB);
clientSocket.getOutputStream().write(dataFrom.getBytes("UTF-8"));
}catch (BindException be){
be.printStackTrace();
}catch(Exception e){
e.printStackTrace();
}finally {
clientSocket.close();
}
}
} catch (Exception e) {
e.printStackTrace();
} finally {
try {
ss.close();
} catch (IOException e) {
e.printStackTrace();
}
}
});
t1.start();
i try using thread but it not working, this code only accept the first data otherwise anoter data will be decline. how to server accept many data at the same time?
Let me tell you how I did it, while playing around with sockets, so I created a SocketServer class
public class Server {
public static final Integer port = 9000;
private final ServerSocket server;
private final ExecutorService service = Executors.newFixedThreadPool(10);
private final AtomicInteger idGenerator = new AtomicInteger(0);
public Server() throws IOException {
this.server = new ServerSocket(port);
}
public void start() {
try {
while (true) {
Worker worker = new Worker(idGenerator.incrementAndGet(), server.accept());
service.execute(worker);
}
} catch (IOException e) {
e.printStackTrace();
}
}
}
Now every time, a client joins, I create a worker thread and submit it to ExecutorService (Executor service has pool of threads and run the passed worker by allocating a thread to it, you can read about it).
The worker class looks like this
public class Worker implements Runnable {
private final Socket client;
private final Logger log = LoggerFactory.getLogger(this.getClass());
public Worker(Integer id, Socket client) {
this.id = id; //Ignore it, it was for logging purpose, how many joined
this.client = client;
}
#Override
public void run() {
listenClientMessages();
closeConnection();
}
private void listenClientMessages() {
final int MAX_INPUT = 1024;
int read;
try (InputStream is = client.getInputStream()) {
byte[] buf = new byte[MAX_INPUT];
while ((read = is.read(buf)) != -1) {
String line = new String(buf, 0, read);
log.info(line);
if (line.equals("bye")) break;
}
} catch (IOException ex) {
ex.printStackTrace();
}
}
private void closeConnection() {
try{
client.close();
}catch (IOException ex) {
ex.printStackTrace();
}
}
}
So, you can see, I am reading bytes in while look
byte[] buf = new byte[MAX_INPUT];
while ((read = is.read(buf)) != -1) {
String line = new String(buf, 0, read);
log.info(line);
if (line.equals("bye")) break;
}
that's why when MAX_INPUT or less is processed, it would wait from client to send next input.
Let me know if it helps.
Edit: As commented by #user207421 in comments, closeConnection function is redundant as inputstream is closed with try-wit-resources block above in listenClientMessages function, so it is not needed.
The program is intended to have multiple clients connect to a single server and the clients are able to send and receive messages among other clients.
For example if Client A says "Hi", Client B and Client C connected to the server would also receive "Hi".
In my current code, the server only receives the messages sent by the clients.
I'm currently looking for a solution to have the server broadcast the message sent by a client (eg. ClientA) to other clients. Any advice would be much appreciated.
This server class handles the connections of multiple clients with the use of threads:
import java.io.*;
import java.net.ServerSocket;
import java.net.Socket;
class EchoThread extends Thread {
private Socket socket;
//constructor
public EchoThread(Socket clientSocket) {
this.socket = clientSocket;
}
#Override
public void run() {
DataInputStream inp = null;
try {
inp = new DataInputStream(new BufferedInputStream(socket.getInputStream()));
//print whatever client is saying as long as it is not "Over"
String line = "";
while (!line.equals("Over")) {
try {
line = inp.readUTF();
System.out.println(line);
} catch (IOException e) { System.out.println(e); }
}
//closes connection when client terminates the connection
System.out.print("Closing Connection");
socket.close();
} catch (IOException e) { System.out.println(e); }
}
}
public class Server {
private static final int PORT = 5000;
public static void main(String args[]) {
ServerSocket serverSocket = null;
Socket socket = null;
//starts the server
try {
serverSocket = new ServerSocket(PORT);
System.out.println("Server started");
System.out.println("Waiting for a client ...\n");
} catch (IOException e) { System.out.println(e); }
//while loop to accept multiple clients
int count = 1;
while(true) {
try {
socket = serverSocket.accept();
System.out.println("Client " + count + " accepted!");
count++;
} catch (IOException e) { System.out.println(e); }
//starts the server thread
new EchoThread(socket).start();
}
}
}
and this is the client class (I have multiple instances of this code running):
import java.net.*;
import java.io.*;
public class ClientA {
private Socket socket = null;
private DataInputStream input = null;
private DataOutputStream output = null;
public ClientA(String address, int port) {
//establish connection
try {
socket = new Socket(address, port);
System.out.println("Connected");
//takes input from terminal
input = new DataInputStream(System.in);
//sends output to the socket
output = new DataOutputStream(socket.getOutputStream());
} catch (IOException e) { System.out.println(e); }
//string to read message from input
String line = "";
//keep reading until "Over" is input
while (!line.equals("Over")) {
try {
line = input.readLine();
output.writeUTF(line);
} catch (IOException e) { System.out.println(e); }
}
//close the connection
try {
input.close();
output.close();
socket.close();
} catch (IOException e) { System.out.println(e); }
}
public static void main (String args[]) {
ClientA client = new ClientA("127.0.0.1", 5000);
}
}
Do feel free to correct me on my code comments as I'm still not very familiar with socket programming.
You did well. Just add a thread to receive message in ClientA; and store socket clients in Server.
In fact, Server is also a "client" when is send message to client.
I add some code based on your code. It works well, hope it's helpful.
class EchoThread extends Thread {
//*****What I add begin.
private static List<Socket> socketList = new ArrayList<>();
//*****What I add end.
private Socket socket;
//constructor
public EchoThread(Socket clientSocket) {
this.socket = clientSocket;
socketList.add(socket);
}
#Override
public void run() {
DataInputStream inp = null;
try {
inp = new DataInputStream(new BufferedInputStream(socket.getInputStream()));
//print whatever client is saying as long as it is not "Over"
String line = "";
while (!line.equals("Over")) {
try {
line = inp.readUTF();
System.out.println(line);
//*****What I add begin.
sendMessageToClients(line);
//*****What I add end.
} catch (IOException e) { System.out.println(e); break;}
}
//closes connection when client terminates the connection
System.out.print("Closing Connection");
socket.close();
} catch (IOException e) { System.out.println(e); }
}
//*****What I add begin.
private void sendMessageToClients(String line) throws IOException {
for (Socket other : socketList) {
if (other == socket) {
continue;//ignore the sender client.
}
DataOutputStream output = new DataOutputStream(other.getOutputStream());
output.writeUTF(line);
}
}
//*****What I add end.
}
public class ClientA {
private Socket socket = null;
private DataInputStream input = null;
private DataOutputStream output = null;
public ClientA(String address, int port) {
//establish connection
try {
socket = new Socket(address, port);
System.out.println("Connected");
//takes input from terminal
input = new DataInputStream(System.in);
//sends output to the socket
output = new DataOutputStream(socket.getOutputStream());
//*****What I add begin.
//Here create a thread to receive message from server.
DataInputStream inp = new DataInputStream(new BufferedInputStream(socket.getInputStream()));
new Thread(() -> {
while (true) {
String str;
try {
str = inp.readUTF();
System.out.println(str);
} catch (IOException e) {
e.printStackTrace();//error.
break;
}
}
}, "Client Reveiver.").start();
//*****What I add end.
} catch (IOException e) { System.out.println(e); }
//string to read message from input
String line = "";
//keep reading until "Over" is input
while (!line.equals("Over")) {
try {
line = input.readLine();
output.writeUTF(line);
} catch (IOException e) { System.out.println(e); }
}
//close the connection
try {
input.close();
output.close();
socket.close();
} catch (IOException e) { System.out.println(e); }
}
I would have a single server thread which would maintain a register of the clients, possibly in a concurrent collection. Then I would send each message received from a client to all other clients.
I'm trying to build a server with Java.
My question is: how to do if I have multiple users at the same time? The answer is: multi threading. But I don't know how to do.
For example, if there is two client connected at the same time, and a server (who does 2*number) : if the client1 say "50" to the server and the client 2 "10", the server is supposed to return "100" to the first client and "20" to the second. But i'm not sure my code works.
Server side:
public class Server {
public static void main(String[] args){
ServerSocket socket;
try {
socket = new ServerSocket(4444);
Thread t = new Thread(new Accept(socket));
t.start();
} catch (IOException e) {
e.printStackTrace();
}
}
class Accept implements Runnable {
private ServerSocket socketserver;
private Socket socket;
private int nbrclient = 1;
public Accept(ServerSocket s){
socketserver = s;
}
public void run() {
try {
socket = socketserver.accept();
in = new BufferedReader (new InputStreamReader (socket.getInputStream()));
String message = in.readLine();
System.out.println(message);
out = new PrintWriter(socket.getOutputStream());
out.println("Pong");
out.flush();
socket.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
Client side:
public class Client {
public static void main(String[] zero) {
Socket socket;
BufferedReader in;
PrintWriter out;
try {
socket = new Socket(InetAddress.getLocalHost(),4444);
out = new PrintWriter(socket.getOutputStream());
out.println("Ping");
out.flush();
in = new BufferedReader (new InputStreamReader (socket.getInputStream()));
String message = in.readLine();
System.out.println(message);
socket.close();
}catch (UnknownHostException e) {
e.printStackTrace();
}catch (IOException e) {
e.printStackTrace();
}
}
}
If you have any ideas (how to do multi-threading and how to verify if my code works, like run two Clients.java and check if the multi-threading works)
The Server sides needs a while loop:
public class Server {
public static void main(String[] args){
ServerSocket socket;
try {
while(true){
socket = new ServerSocket(4444);
Socket socketInstance = socket.accept();
Thread t = new Thread(new Accept(socketInstance));
t.start();
}
} catch (IOException e) {
e.printStackTrace();
}
}
class Accept implements Runnable {
private Socket socket;
private int nbrclient = 1;
public Accept(Socket s){
socket = s;
}
public void run() {
try {
in = new BufferedReader (new InputStreamReader (socket.getInputStream()));
String message = in.readLine();
System.out.println(message);//this message should be your number
Double number = Double.parseString(message);
out = new PrintWriter(socket.getOutputStream());
//out.println("Pong");
out.println(2*number +"");
out.flush();
socket.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
The client side looks ok. Just replace out.println("Ping"); with out.println("50"); or whatever you want.
You first start the server and then you can start multiple client applications. If you have any errors you can then post them here and have a look on an exact scenario.
Currently I am working on a server/client application which sends data using java with Runnable and threads. The problem is that the client is sending the data and when the server starts to read it the client has already finished and closed the connection which on the server side only a partially of the data is arrived, can they be setup to be synchronized?
this is the client:
private void ConnectionToServer(final String ipAddress, final int Port) {
final ExecutorService clientProcessingPool = Executors.newFixedThreadPool(10);
Runnable serverTask = new Runnable() {
#Override
public void run() {
try {
socket = new Socket(ipAddress, Port);
bos = new BufferedOutputStream(socket.getOutputStream());
dos = new DataOutputStream(socket.getOutputStream());
File f = new File("C:/Users/lukeLaptop/Downloads/RemoveWAT22.zip");
String data = f.getName()+f.length();
byte[] b = data.getBytes();
sendBytes(b, 0, b.length);
dos.flush();
bos.flush();
bis.close();
dos.close();
//clientProcessingPool.submit(new ServerTask(socket));
} catch (IOException ex) {
Logger.getLogger(ClientClass.class.getName()).log(Level.SEVERE, null, ex); } finally {
}
}
};
Thread serverThread = new Thread(serverTask);
serverThread.start();
public void sendBytes(byte[] myByteArray, int start, int len) throws IOException {
if (len < 0) {
throw new IllegalArgumentException("Negative length not allowed");
}
if (start < 0 || start >= myByteArray.length) {
throw new IndexOutOfBoundsException("Out of bounds: " + start);
}
// Other checks if needed.
// May be better to save the streams in the support class;
// just like the socket variable.
OutputStream out = socket.getOutputStream();
DataOutputStream dos = new DataOutputStream(out);
dos.writeInt(len);
if (len > 0) {
dos.write(myByteArray, start, len);
}
}
server code:
private void acceptConnection() {
try {
final ExecutorService clientProcessingPool = Executors.newFixedThreadPool(10);
Runnable serverTask = new Runnable() {
#Override
public void run() {
try {
ServerSocket server = new ServerSocket(8080);
while (true) {
socket = server.accept();
System.out.println("Got a client !");
bis = new BufferedInputStream(socket.getInputStream());
dis = new DataInputStream(socket.getInputStream());
String data = readBytes().toString();
System.out.println(data);
bos.close();
dis.close();
//clientProcessingPool.submit(new ClientTask(socket));
}
} catch (IOException ex) {
System.out.println(ex.getMessage());
}
}
};
Thread serverThread = new Thread(serverTask);
serverThread.start();
} catch (Exception io) {
io.printStackTrace();
}
}
public byte[] readBytes() throws IOException {
// Again, probably better to store these objects references in the support class
InputStream in = socket.getInputStream();
DataInputStream dis = new DataInputStream(in);
int len = dis.readInt();
byte[] data = new byte[len];
if (len > 0) {
dis.readFully(data);
}
return data;
}
You mixed up many things:
Variables start most of the time with a lowercase letter, e.g. int port, int ipAddress
Classes start with a uppercase letter, e.g. Client, Server
only open one Data*stream on a socket. new DataInputStream(socket.getInputStream()) or new BufferedInputStream(socket.getInputStream()), but not both
If you need both, chain them: new DataInputStream(new BufferedInputStream(socket.getInputStream()));
KISS (Keep it short & simple)
If you use a DataInputStream, then use the given functionality of sending objects and primitives, e.g. sendUTF(), sendInt(), sendShort(), and so on...
Name your vars right: servertask is a client thread? no
Move long anonymous classes to a new class
Don't use port 8080, this port is used for many other application and will cause problems
example code regarding your example an my advices:
Server
public class Server implements Runnable {
private void acceptConnection() {
Thread serverThread = new Thread(this);
serverThread.start();
}
#Override
public void run() {
try {
ServerSocket server = new ServerSocket(8081);
while (true) {
Socket socket = server.accept();
System.out.println("Got a client !");
// either open the datainputstream directly
DataInputStream dis = new DataInputStream(socket.getInputStream());
// or chain them, but do not open two different streams:
// DataInputStream dis = new DataInputStream(new BufferedInputStream(socket.getInputStream()));
// Your DataStream allows you to read/write objects, use it!
String data = dis.readUTF();
System.out.println(data);
dis.close();
// in case you have a bufferedInputStream inside of Datainputstream:
// you do not have to close the bufferedstream
}
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
public static void main(String[] args) {
new Server().acceptConnection();
}
}
description:
main: create a new Server Object, which is a Runnable
acceptConnections: create a Thread
run:
open a Serversocket
wait for a connection
open exactly one stream
read the Data
close the stream and wait for next connection
Client
public class Client {
private static void sendToServer(String ipAddress, int port) throws UnknownHostException, IOException {
Socket socket = new Socket(ipAddress, port);
// same here, only open one stream
DataOutputStream dos = new DataOutputStream(socket.getOutputStream());
File f = new File("C:/Users/lukeLaptop/Downloads/RemoveWAT22.zip");
String data = f.getName()+f.length();
dos.writeUTF(data);
dos.flush();
dos.close();
}
public static void main(String[] args) throws UnknownHostException, IOException {
Client.sendToServer("localhost", 8081);
}
}
description (This one is straight forward):
open socket
open DataStream
send Data
flush and close
I'm developing an asynchronous socket client based on threads. When the program calls readLine(), it blocks indefinitely and never returns.
public class ADNClient {
Socket socket = null;
DataOutputStream dataOutputStream = null;
DataInputStream dataInputStream = null;
Thread listener = new Thread(new Runnable() {
#Override
public void run() {
String line;
try {
// Stop here and doesn't progress
while ((line = dataInputStream.readLine()) != null) {
//DO something
}
}
catch (IOException e) {}
});
public ADNClient() {
try {
socket = new Socket("192.168.1.5", 5000);
dataOutputStream = new DataOutputStream(socket.getOutputStream());
dataInputStream = new DataInputStream(socket.getInputStream());
listener.start();
//sender.start();
} catch (Exception e) {
Log.e("ADN", e.getMessage());
}
}
public void close() {
listener.stop();
try {
socket.close();
} catch (IOException e) {
Log.e("ADN", e.getMessage());
}
}
}
Ok... I'm noob with IN/Outputstreams... I didn't send the newline character, the correct way to recive information is using
readUTF()
instead of
readLine()
Thank you Greg Kopff!