I wrote a Simple Server Client Program and when I start the Server and the Client, the Client gets the message which it sent to the Server back and terminates itself. But when i start another Client it does not get the message back. Why?
Thanks alot!
First class: the client
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.OutputStream;
import java.io.PrintStream;
import java.net.Socket;
import java.net.UnknownHostException;
public class StringClient {
public static void main(String[] args) {
Socket socket = null;
try{
socket = new Socket("localhost", 3141);
OutputStream raus = socket.getOutputStream();
PrintStream ps = new PrintStream(raus, true);
System.out.println("1");
ps.println("Hello World!");
ps.println("Hello Universe!");
InputStream rein = socket.getInputStream();
System.out.println("verf\u00FCgbare Bytes: " + rein.available());
BufferedReader br =new BufferedReader(new InputStreamReader(rein));
System.out.println(2);
while(br.ready()){
System.out.println(br.readLine());
}
}catch(UnknownHostException e ){
System.out.println("Unknown Host...");
e.printStackTrace();
} catch (IOException e) {
System.out.println("IOProbleme...");
e.printStackTrace();
}finally{
if(socket != null){
try{
socket.close();
System.out.println("Socket geschlossen...");
}catch(IOException e){
System.out.println("Fehler beim Schließen des Sockets!");
e.printStackTrace();
}
}
}
}
}
Second class: the Server
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.PrintStream;
import java.net.ServerSocket;
import java.net.Socket;
public class StringServer {
private final ServerSocket server;
public StringServer(int port) throws IOException {
server = new ServerSocket(port);
}
private void connect(){
while(true){
Socket socket = null;
try{
socket = server.accept();
reinRaus(socket);
}catch(IOException e){
e.printStackTrace();
}finally{
if(socket != null){
try{
socket.close();
}catch(IOException e){
e.printStackTrace();
}
}
}
}
}
private void reinRaus(Socket socket) throws IOException{
BufferedReader rein = new BufferedReader(new InputStreamReader(socket.getInputStream()));
PrintStream raus = new PrintStream(socket.getOutputStream());
String s;
while(rein.ready()){
s = rein.readLine();
raus.println(s);
}
}
public static void main(String[] args) throws IOException {
StringServer server = new StringServer(3141);
server.connect();
}
}
The main thread should allocates individual/different threads to the incoming clients, so different clients get allocated for different threads (they get different sockets). In your current code there's only a server serving a client.
StringServer.java
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.PrintStream;
import java.net.ServerSocket;
import java.net.Socket;
public class StringServer {
private final ServerSocket server;
public StringServer(int port) throws IOException {
server = new ServerSocket(port);
}
private void connect(){
while(true){
Socket socket = null;
try{
socket = server.accept();
clientHandler ch = new clientHandler(socket);
ch.start();
}catch(IOException e){
e.printStackTrace();
}finally{
if(socket != null){
try{
socket.close();
}catch(IOException e){
e.printStackTrace();
}
}
}
}
}
public static void main(String[] args) throws IOException {
StringServer server = new StringServer(3541);
server.connect();
}
}
class clientHandler extends Thread {
Socket client;
public clientHandler(Socket client) {
this.client = client;
}
#Override
public void run() {
try {
BufferedReader rein = new BufferedReader(new InputStreamReader(client.getInputStream()));
PrintStream raus = new PrintStream(client.getOutputStream(),true);
String s;
while(rein.ready()){
s = rein.readLine();
raus.println(s);
}
client.close(); // IOException
} catch (IOException e) {
}
}
}
StringClient.java
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.OutputStream;
import java.io.PrintStream;
import java.net.Socket;
import java.net.UnknownHostException;
public class StringClient {
public static void main(String[] args) {
Socket socket = null;
try{
socket = new Socket("localhost", 3541);
OutputStream raus = socket.getOutputStream();
PrintStream ps = new PrintStream(raus, true);
System.out.println("1");
ps.println("Hello World!");
ps.println("Hello Universe!");
InputStream rein = socket.getInputStream();
System.out.println("verf\u00FCgbare Bytes: " + rein.available());
BufferedReader br =new BufferedReader(new InputStreamReader(rein));
System.out.println(2);
while(br.ready()){
System.out.println(br.readLine());
}
}catch(UnknownHostException e ){
System.out.println("Unknown Host...");
e.printStackTrace();
} catch (IOException e) {
System.out.println("IOProbleme...");
e.printStackTrace();
}finally{
if(socket != null){
try{
socket.close();
System.out.println("Socket geschlossen...");
}catch(IOException e){
System.out.println("Fehler beim Schließen des Sockets!");
e.printStackTrace();
}
}
}
}
}
Related
i'm developing a Java App, but i have a big problem. I'm trying to develop a client-server app, so that the client could retrieve information managed by a server.
The problem is that, when the connection is established, probably goes in loop, near two specifics lines of code (cause if i delete this lines, it goes on):
out = new ObjectOutputStream(socket.getOutputStream());
in = new ObjectInputStream(socket.getInputStream());
I'm an University Student and the client.java has been delivered by professor, so i do not think that this could have problem, but you never know. Now i post 3 files:
MultiServer: used to manage multiclients connection
ServerOneClient: to implements the protocol
Client.java
package server;
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.net.ServerSocket;
import java.net.Socket;
import com.mysql.cj.xdevapi.Client;
public class MultiServer {
private int PORT = 2025;
private void run() throws IOException
{
ServerSocket serverSocket = new ServerSocket(PORT);
Socket clientSocket = null;
BufferedReader in=null;
PrintWriter out=null;
try {
clientSocket = serverSocket.accept();
System.out.println("Connection Accepted");
//stream di input
InputStreamReader isr = new InputStreamReader(clientSocket.getInputStream());
in = new BufferedReader(isr);
//creazione stream di output
OutputStreamWriter osw = new OutputStreamWriter(clientSocket.getOutputStream());
BufferedWriter bw = new BufferedWriter(osw);
out = new PrintWriter(bw, true);
//ciclo di ricezione dal client e invio risposta
while(true)
{
String str = in.readLine();
if(str.equals("END")) break;
System.out.println("Echoing: " + str);
out.println(str);
}
}
catch (IOException e)
{
System.err.println("Accept failed");
System.exit(1);
}
//chiusura di stream e socket
System.out.println("Echoserver: closing..");
out.close();
in.close();
clientSocket.close();
serverSocket.close();
}
public MultiServer(int port) throws IOException {
PORT=port;
run();
}
public static void main(String[] args) throws IOException
{
MultiServer s = new MultiServer(2025);
s.run();
}
}
ServerOneClient.java
package server;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.ObjectInputStream;
import java.io.ObjectOutputStream;
import java.net.ServerSocket;
import java.net.Socket;
public class ServerOneClient extends Thread {
private Socket socket;
private ObjectInputStream in;
private ObjectOutputStream out;
public ServerOneClient(Socket s) throws IOException {
socket = s;
in = new ObjectInputStream(s.getInputStream());
out = new ObjectOutputStream(s.getOutputStream());
start();
}
public void run()
{
super.run();
}
}
Client.java
package client;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.ObjectInputStream;
import java.io.ObjectOutputStream;
import java.io.OutputStream;
import java.io.OutputStreamWriter;
import java.net.InetAddress;
import java.net.Socket;
import java.net.UnknownHostException;
import utility.Keyboard;
public class Client {
private Socket socket=null;
private ObjectOutputStream out=null;
private ObjectInputStream in=null;
/**
* #param args
* #throws IOException
* #throws ClassNotFoundException
*/
Client (String address, int port) throws IOException, ClassNotFoundException{
socket = new Socket(address, port);
System.out.println(socket);
talking();
}
private void talking() throws IOException, ClassNotFoundException {
int decision=0;
out = new ObjectOutputStream(socket.getOutputStream());
in = new ObjectInputStream(socket.getInputStream()); // stream con richieste del client
String menu="";
do {
do{
System.out.println("Load KNN from file [1]");
System.out.println("Load KNN from binary file [2]");
System.out.println("Load KNN from database [3]");
decision=Keyboard.readInt();
}while(decision <0 || decision >3);
String risposta="";
do {
out.writeObject(decision);
String tableName="";
System.out.println("Table name (without estensione):");
tableName=Keyboard.readString();
out.writeObject(tableName);
risposta=(String)in.readObject();
}while(risposta.contains("#ERROR"));
System.out.println("KNN loaded on the server");
// predict
String c;
do {
out.writeObject(4);
boolean flag=true; //reading example
do {
risposta=(String)(in.readObject());
if(!risposta.contains("#ENDEXAMPLE")) {
// sto leggendo l'esempio
String msg=(String)(in.readObject());
if(risposta.equals("#READSTRING")) //leggo una stringa
{
System.out.println(msg);
out.writeObject(Keyboard.readString());
}
else //leggo un numero
{
double x=0.0;
do {
System.out.println(msg);
x=Keyboard.readDouble();
}
while(new Double(x).equals(Double.NaN));
out.writeObject(x);
}
}
else flag=false;
}while( flag);
//sto leggendo k
risposta=(String)(in.readObject());
int k=0;
do {
System.out.print(risposta);
k=Keyboard.readInt();
}while (k<1);
out.writeObject(k);
//aspetto la predizione
System.out.println("Prediction:"+in.readObject());
System.out.println("Vuoi ripetere predizione? Y/N");
c=Keyboard.readString();
}while (c.toLowerCase().equals("y"));
System.out.println("Vuoi ripetere una nuova esecuzione con un nuovo oggetto KNN? (Y/N)");
menu=Keyboard.readString();
}
while(menu.toLowerCase().equals("y"));
}
public static void main(String[] args){
InetAddress addr;
try {
addr = InetAddress.getByName("localhost");
} catch (UnknownHostException e) {
System.out.println(e.toString());
return;
}
Client c;
try {
c=new Client("localhost", 2025);
} catch (IOException e) {
System.out.println(e.toString());
return;
} catch (NumberFormatException e) {
System.out.println(e.toString());
return;
} catch (ClassNotFoundException e) {
System.out.println(e.toString());
return;
}
}
}
Hope you can help me, for any doubt, i'm here!
I have to do a project in Java for an exam which has to have multi-client sockets.
We have some example code for sockets from our teacher - and I modified it a bit. The problem is that it only receives data once, and then it stops. I found that out by printing the received data into the console.
So here's my the code:
Server.java
package socket;
import database.models.PersoanaEntity;
import java.io.IOException;
import java.net.ServerSocket;
import java.net.Socket;
public class Server {
public static final int PORT = 27015;
public void start() {
new Thread(() -> {
try {
ServerSocket serverSocket = new ServerSocket(PORT);
Socket clientSocket = null;
boolean isClose = false;
System.out.println("Server is running");
while (!isClose) {
clientSocket = serverSocket.accept();
new Thread(new ServerThread(clientSocket)).start();
}
serverSocket.close();
} catch (IOException e) {
e.printStackTrace();
}
}).start();
}
}
ServerThread.java
package socket;
import database.models.PersoanaEntity;
import org.json.JSONObject;
import java.io.IOException;
import java.io.ObjectInputStream;
import java.io.ObjectOutputStream;
import java.net.Socket;
public class ServerThread extends Thread{
private Socket socket = null;
private ObjectInputStream in = null;
private ObjectOutputStream out = null;
PersoanaEntity loggedInPerson = new PersoanaEntity();
public ServerThread(Socket socket) {
this.socket = socket;
try {
//For receiving and sending data
this.in = new ObjectInputStream(socket.getInputStream());
this.out = new ObjectOutputStream(socket.getOutputStream());
} catch (IOException e) {
e.printStackTrace();
}
}
public void run() {
try {
String received = this.in.readObject().toString();
System.out.println(received);
JSONObject jsonObject = new JSONObject(received);
execute(received);
} catch (IOException e) {
e.printStackTrace();
} catch (ClassNotFoundException e) {
e.printStackTrace();
}
}
private void execute(String message) {
JSONObject jo = new JSONObject(message);
ProcessInput pi = new ProcessInput();
pi.processInput(jo, this.out);
}
}
ProcessInput.java
package socket;
import database.daos.PersoanaDao;
import database.models.PersoanaEntity;
import jakarta.persistence.NoResultException;
import org.json.JSONObject;
import java.io.IOException;
import java.io.ObjectOutputStream;
import java.util.Optional;
public class ProcessInput {
void processInput(JSONObject data, ObjectOutputStream out) {
switch (data.get("type").toString())
{
case "LOGIN_USER":
PersoanaDao persoanaDao = new PersoanaDao();
String username = data.get("username").toString();
JSONObject json = new JSONObject();
try {
PersoanaEntity persoanaEntity = persoanaDao.get(username);
json.put("status_code", "200");
} catch(Exception e) {
json.put("status_code", "404");
}
try {
out.writeObject(json.toString());
} catch (IOException e)
{
System.out.println(e.toString());
}
break;
}
}
}
I won't add the code from the client side because I'm quite sure the problem is from the server after doing some tests. I think that it happens because the run method is only called once, AFAIK, and that is when .start() is called from the Thread.
Then it won't ever be called again so there will never be data in the received string.
Am I right?
If so, what's the fix?
If not, why am I getting data only once and how can I fix it?
//edit: I will add the client just in case:
package socket;
import org.json.JSONObject;
import java.io.IOException;
import java.io.ObjectInputStream;
import java.io.ObjectOutputStream;
import java.net.Socket;
import java.util.Scanner;
public enum Client implements Runnable {
INSTANCE;
public static final int PORT = 27015;
public Socket getSocket() {
return socket;
}
public ObjectInputStream getInputStream() {
return inputStream;
}
public ObjectOutputStream getOutputStream() {
return outputStream;
}
private Socket socket = null;
private ObjectInputStream inputStream = null;
private ObjectOutputStream outputStream = null;
private String name;
Client() {
try {
socket = new Socket("localhost", PORT);
this.outputStream = new ObjectOutputStream(socket.getOutputStream());
this.inputStream = new ObjectInputStream(socket.getInputStream());
} catch(Exception e) {
System.out.println("Connection error");
}
}
public void run() {
System.out.println("Client socket running");
//For receiving data
boolean isClose = false;
while (!isClose) {
}
try {
socket.close();
} catch (Exception e) {
System.out.println(e.getMessage());
}
}
}
I have problem in this code that client could send message to server but it doesn't receive the message sent from server I've debugged the server code it does everything as well as it should be but client sided it does all the code until message=br.readLine() , it sticks on there
server code
package server;
import java.io.BufferedReader;
import java.io.EOFException;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.PrintWriter;
import java.net.ServerSocket;
import java.net.Socket;
public class server {
static Socket s;
static ServerSocket ss;
static InputStreamReader isr;
static BufferedReader br;
static String message;
static PrintWriter pw;
public server(){
try {
ss=new ServerSocket(8080);
while(true){
s=ss.accept();
isr=new InputStreamReader(s.getInputStream());
br=new BufferedReader(isr);
message=br.readLine();
System.out.println(message);
pw=new PrintWriter(s.getOutputStream(),true);
pw.write("returned back from server to client");
System.out.println("message sent");
pw.flush();
pw.close();
isr.close();
s.close();
}
} catch (EOFException eofException) {
// TODO Auto-generated catch block
eofException.printStackTrace();
}catch(IOException e){
e.printStackTrace();
}
}
public static void main(String[]args){
server s=new server();
}
}
client code
package com.example.myapplication;
import android.os.AsyncTask;
import java.io.BufferedReader;
import java.io.DataOutputStream;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.PrintWriter;
import java.net.Socket;
public class ClientSender extends AsyncTask<String,Void,Void> {
Socket s;
DataOutputStream dos;
InputStreamReader isr;
BufferedReader br;
PrintWriter pw;
#Override
protected Void doInBackground(String... voids) {
String message = voids[0];
try {
System.out.println("1");
s = new Socket("0.0.0.0", 8080);
pw = new PrintWriter(s.getOutputStream());
pw.write(message);
pw.flush();
pw.close();
s.close();
} catch (IOException e) {
e.printStackTrace();
}
try {
System.out.println("2");
s = new Socket("0.0.0.0", 8080);
System.out.println("connected to the server");
isr = new InputStreamReader(s.getInputStream());
System.out.println("3");
br = new BufferedReader(isr);
System.out.println("4");
message = br.readLine();
System.out.println(message);
isr.close();
s.close();
System.out.println("5");
} catch (IOException e) {
e.printStackTrace();
}
return null;
}
}
I would suggest you to use Socket.IO instead of writting your own socket client. It's a well-tested and well-documented lib. This will make your life pretty much easier.
How do you handle multiple client to connect to one server? I have this LogServer.java
import javax.net.ssl.*;
import javax.net.*;
import java.io.*;
import java.net.*;
public class LogServer {
private static final int PORT_NUM = 5000;
public static void main(String args[]) {
ServerSocketFactory serverSocketFactory =
ServerSocketFactory.getDefault();
ServerSocket serverSocket = null;
try {
serverSocket =
serverSocketFactory.createServerSocket(PORT_NUM);
} catch (IOException ignored) {
System.err.println("Unable to create server");
System.exit(-1);
}
System.out.printf("LogServer running on port: %s%n", PORT_NUM);
while (true) {
Socket socket = null;
try {
socket = serverSocket.accept();
InputStream is = socket.getInputStream();
BufferedReader br = new BufferedReader(
new InputStreamReader(is, "US-ASCII"));
String line = null;
while ((line = br.readLine()) != null) {
System.out.println(line);
}
} catch (IOException exception) {
// Just handle next request.
} finally {
if (socket != null) {
try {
socket.close();
} catch (IOException ignored) {
}
}
}
}
}
}
and an embedded applet with part of the code like this e.g
import java.io.*;
import java.util.logging.*;
public class LogTest
{
private static Logger logger = Logger.getAnonymousLogger();
public static void main(String argv[]) throws IOException
{
Handler handler = new SocketHandler("localhost", 5000);
logger.addHandler(handler);
logger.log(Level.SEVERE, "Hello, World");
logger.log(Level.SEVERE, "Welcome Home");
logger.log(Level.SEVERE, "Hello, World");
logger.log(Level.SEVERE, "Welcome Home");
}
}
now the question is if I run "java LogServer" on the server, it will open the application and waiting for input stream and if I open my site, it will start streaming the log. But if I open one more using other computer/network, the second site does not log the stream. seems like it's because the first one still bind to port 5000.
How do I handle this?
How does socket actually work with multiple client / one server?
For every client you need to start separate thread. Example:
public class ThreadedEchoServer {
static final int PORT = 1978;
public static void main(String args[]) {
ServerSocket serverSocket = null;
Socket socket = null;
try {
serverSocket = new ServerSocket(PORT);
} catch (IOException e) {
e.printStackTrace();
}
while (true) {
try {
socket = serverSocket.accept();
} catch (IOException e) {
System.out.println("I/O error: " + e);
}
// new thread for a client
new EchoThread(socket).start();
}
}
}
and
public class EchoThread extends Thread {
protected Socket socket;
public EchoThread(Socket clientSocket) {
this.socket = clientSocket;
}
public void run() {
InputStream inp = null;
BufferedReader brinp = null;
DataOutputStream out = null;
try {
inp = socket.getInputStream();
brinp = new BufferedReader(new InputStreamReader(inp));
out = new DataOutputStream(socket.getOutputStream());
} catch (IOException e) {
return;
}
String line;
while (true) {
try {
line = brinp.readLine();
if ((line == null) || line.equalsIgnoreCase("QUIT")) {
socket.close();
return;
} else {
out.writeBytes(line + "\n\r");
out.flush();
}
} catch (IOException e) {
e.printStackTrace();
return;
}
}
}
}
You can also go with more advanced solution, that uses NIO selectors, so you will not have to create thread for every client, but that's a bit more complicated.
This is the echo server handling multiple clients... Runs fine and good using Threads
// echo 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;
public class Server_X_Client {
public static void main(String args[]){
Socket s=null;
ServerSocket ss2=null;
System.out.println("Server Listening......");
try{
ss2 = new ServerSocket(4445); // can also use static final PORT_NUM , when defined
}
catch(IOException e){
e.printStackTrace();
System.out.println("Server error");
}
while(true){
try{
s= ss2.accept();
System.out.println("connection Established");
ServerThread st=new ServerThread(s);
st.start();
}
catch(Exception e){
e.printStackTrace();
System.out.println("Connection Error");
}
}
}
}
class ServerThread extends Thread{
String line=null;
BufferedReader is = null;
PrintWriter os=null;
Socket s=null;
public ServerThread(Socket s){
this.s=s;
}
public void run() {
try{
is= new BufferedReader(new InputStreamReader(s.getInputStream()));
os=new PrintWriter(s.getOutputStream());
}catch(IOException e){
System.out.println("IO error in server thread");
}
try {
line=is.readLine();
while(line.compareTo("QUIT")!=0){
os.println(line);
os.flush();
System.out.println("Response to Client : "+line);
line=is.readLine();
}
} catch (IOException e) {
line=this.getName(); //reused String line for getting thread name
System.out.println("IO Error/ Client "+line+" terminated abruptly");
}
catch(NullPointerException e){
line=this.getName(); //reused String line for getting thread name
System.out.println("Client "+line+" Closed");
}
finally{
try{
System.out.println("Connection Closing..");
if (is!=null){
is.close();
System.out.println(" Socket Input Stream Closed");
}
if(os!=null){
os.close();
System.out.println("Socket Out Closed");
}
if (s!=null){
s.close();
System.out.println("Socket Closed");
}
}
catch(IOException ie){
System.out.println("Socket Close Error");
}
}//end finally
}
}
Also here is the code for the client.. Just execute this code for as many times as you want to create multiple client..
// A simple Client Server Protocol .. Client for Echo Server
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.PrintWriter;
import java.net.InetAddress;
import java.net.Socket;
public class NetworkClient {
public static void main(String args[]) throws IOException{
InetAddress address=InetAddress.getLocalHost();
Socket s1=null;
String line=null;
BufferedReader br=null;
BufferedReader is=null;
PrintWriter os=null;
try {
s1=new Socket(address, 4445); // You can use static final constant PORT_NUM
br= new BufferedReader(new InputStreamReader(System.in));
is=new BufferedReader(new InputStreamReader(s1.getInputStream()));
os= new PrintWriter(s1.getOutputStream());
}
catch (IOException e){
e.printStackTrace();
System.err.print("IO Exception");
}
System.out.println("Client Address : "+address);
System.out.println("Enter Data to echo Server ( Enter QUIT to end):");
String response=null;
try{
line=br.readLine();
while(line.compareTo("QUIT")!=0){
os.println(line);
os.flush();
response=is.readLine();
System.out.println("Server Response : "+response);
line=br.readLine();
}
}
catch(IOException e){
e.printStackTrace();
System.out.println("Socket read Error");
}
finally{
is.close();os.close();br.close();s1.close();
System.out.println("Connection Closed");
}
}
}
I guess the problem is that you need to start a separate thread for each connection and call serverSocket.accept() in a loop to accept more than one connection.
It is not a problem to have more than one connection on the same port.
See O'Reilly "Java Cookbook", Ian Darwin - recipe 17.4 Handling Multiple Clients.
Pay attention that accept() is not thread safe, so the call is wrapped within synchronized.
64: synchronized(servSock) {
65: clientSocket = servSock.accept();
66: }
Here is code for Multiple Client to one Server Working Fine ..
Give it a try :)
Server.java:
import java.io.DataInputStream;
import java.io.IOException;
import java.net.ServerSocket;
import java.net.Socket;
import java.util.logging.Level;
import java.util.logging.Logger;
class Multi extends Thread{
private Socket s=null;
DataInputStream infromClient;
Multi() throws IOException{
}
Multi(Socket s) throws IOException{
this.s=s;
infromClient = new DataInputStream(s.getInputStream());
}
public void run(){
String SQL=new String();
try {
SQL = infromClient.readUTF();
} catch (IOException ex) {
Logger.getLogger(Multi.class.getName()).log(Level.SEVERE, null, ex);
}
System.out.println("Query: " + SQL);
try {
System.out.println("Socket Closing");
s.close();
} catch (IOException ex) {
Logger.getLogger(Multi.class.getName()).log(Level.SEVERE, null, ex);
}
}
}
public class Server {
public static void main(String args[]) throws IOException,
InterruptedException{
while(true){
ServerSocket ss=new ServerSocket(11111);
System.out.println("Server is Awaiting");
Socket s=ss.accept();
Multi t=new Multi(s);
t.start();
Thread.sleep(2000);
ss.close();
}
}
}
Client1.java:
import java.io.DataOutputStream;
import java.io.ObjectInputStream;
import java.net.Socket;
public class client1 {
public static void main(String[] arg) {
try {
Socket socketConnection = new Socket("127.0.0.1", 11111);
//QUERY PASSING
DataOutputStream outToServer = new DataOutputStream(socketConnection.getOutputStream());
String SQL="I am client 1";
outToServer.writeUTF(SQL);
} catch (Exception e) {System.out.println(e); }
}
}
Client2.java
import java.io.DataOutputStream;
import java.net.Socket;
public class client2 {
public static void main(String[] arg) {
try {
Socket socketConnection = new Socket("127.0.0.1", 11111);
//QUERY PASSING
DataOutputStream outToServer = new DataOutputStream(socketConnection.getOutputStream());
String SQL="I am Client 2";
outToServer.writeUTF(SQL);
} catch (Exception e) {System.out.println(e); }
}
}
I have a project that has a server which creates an empty text file.
Once my client stops writing to this file, the server should read and display the results.
My problem is that the client is connecting to the server, but whatever text the client is sending is not being written on the server side. In addition, when I exit, the server doesn't quit.
This is what I have so far:
The Server
import java.io.BufferedReader;
import java.io.BufferedWriter;
import java.io.DataInputStream;
import java.io.File;
import java.io.FileWriter;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.ObjectInputStream;
import java.io.ObjectOutputStream;
import java.io.OutputStream;
import java.io.OutputStreamWriter;
import java.io.PrintStream;
import java.io.PrintWriter;
import java.net.ServerSocket;
import java.net.Socket;
import java.util.Scanner;
public class Server {
public static void main(String args[]) throws IOException {
BufferedWriter out;// = new BufferedWriter(new FileWriter("C://Users//Vagos//Desktop//file.txt"));
ServerSocket echoServer = null;
String line;
DataInputStream is;
PrintStream os;
Socket clientSocket = null;
// Try to open a server socket on port 9999
try {
echoServer = new ServerSocket(55);
}
catch (IOException e) {
System.out.println(e);
}
// Create a socket object from the ServerSocket to listen and accept
// connections.
// Open input and output streams
try {
clientSocket = echoServer.accept();
is = new DataInputStream(clientSocket.getInputStream());
os = new PrintStream(clientSocket.getOutputStream());
out = new BufferedWriter(new FileWriter("C://Users//Vagos//Desktop//file.txt"));
// As long as we receive data, echo that data back to the client.
while (true) {
line = is.readUTF();
os.println(line);
os.flush();
out.write(line);
out.flush();
}
}
catch (IOException e) {
System.out.println(e);
}
}
}
Here is my client:
import java.io.*;
import java.net.InetAddress;
import java.net.ServerSocket;
import java.net.Socket;
import java.net.UnknownHostException;
import java.util.Scanner;
public class client {
public static void main(String[] args) {
Socket smtpSocket = null;
DataOutputStream os = null;
DataInputStream is = null;
String strout;
Scanner in = new Scanner(System.in);
try {
smtpSocket = new Socket("localhost", 55);
os = new DataOutputStream(smtpSocket.getOutputStream());
is = new DataInputStream(smtpSocket.getInputStream());
} catch (UnknownHostException e) {
System.err.println("Don't know about host: hostname");
} catch (IOException e) {
System.err.println("Couldn't get I/O for the connection to: hostname");
}
if (smtpSocket != null && os != null && is != null) {
try {
do{
System.out.print("Write what the client will send: ");
strout = in.nextLine();
os.writeBytes(strout);}
while(!strout.equals("exit"));
os.close();
is.close();
smtpSocket.close();
} catch (UnknownHostException e) {
System.err.println("Trying to connect to unknown host: " + e);
} catch (IOException e) {
System.err.println("IOException: " + e);
}
}
}
};
Try this.
In your server
// Open input and output streams
try {
clientSocket = echoServer.accept();
is = new DataInputStream(clientSocket.getInputStream());
InputStreamReader ir = new InputStreamReader(is);
BufferedReader br = new BufferedReader(ir);
os = new PrintStream(clientSocket.getOutputStream());
out = new BufferedWriter(new FileWriter("C://Users//Vagos//Desktop//file.txt"));
// As long as we receive data, echo that data back to the client.
while (true) {
line = br.readLine();
System.out.println(line);
os.println(line);
os.flush();
if( line != null ){
out.write(line + '\n');
out.flush();
}
}
}
And about the 'exit' part of your client try after changing
while(!strout.equals("exit"));
to
while(!strout.equalsIgnoreCase("exit"));
Hope this helps !!
Today my teacher is upload a new project because he has make a false , the project i have to make is similar which the old but the client is reading or writing a txt with number from 0-911, The client is choice randomly what is make read o write if choice read show the numbers of txt if choice write he write randomly a number from 0-911 and stop if choice the 100.
i make it but nothing show me is stack.
sever
import java.io.BufferedReader;
import java.io.BufferedWriter;
import java.io.DataInputStream;
import java.io.File;
import java.io.FileWriter;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.ObjectInputStream;
import java.io.ObjectOutputStream;
import java.io.OutputStream;
import java.io.OutputStreamWriter;
import java.io.PrintStream;
import java.io.PrintWriter;
import java.net.ServerSocket;
import java.net.Socket;
import java.util.Scanner;
public class Server {
public static void main(String args[]) throws IOException {
BufferedWriter out;// = new BufferedWriter(new FileWriter("C://Users//Vagos//Desktop//file.txt"));
ServerSocket echoServer = null;
int line;
DataInputStream is;
PrintStream os;
Socket clientSocket = null;
// Try to open a server socket on port 9999
try {
echoServer = new ServerSocket(55);
}
catch (IOException e) {
System.out.println(e);
}
// Create a socket object from the ServerSocket to listen and accept
// connections.
// Open input and output streams
try {
clientSocket = echoServer.accept();
is = new DataInputStream(clientSocket.getInputStream());
InputStreamReader ir = new InputStreamReader(is);
BufferedReader br = new BufferedReader(ir);
os = new PrintStream(clientSocket.getOutputStream());
out = new BufferedWriter(new FileWriter("C://Users//Vagos//Desktop//file.txt"));
// As long as we receive data, echo that data back to the client.
boolean ch=true;
{
line =(Integer) br.read();
// System.out.println(line);
os.println(line);
os.flush();
out.write(line+"\n");
out.flush();
} while (line != 100);
os.close();
out.close();
br.close();
clientSocket.close();
}
catch (IOException e) {
System.out.println(e);
}
}
}
client
import java.io.*;
import java.net.InetAddress;
import java.net.ServerSocket;
import java.net.Socket;
import java.net.UnknownHostException;
import java.util.Random;
import java.util.Scanner;
public class client {
public static void main(String[] args) throws IOException {
Socket smtpSocket = null;
DataOutputStream os = null;
DataInputStream is = null;
String strout;
int number=0;
Random rand = new Random(System.currentTimeMillis());
Scanner in = new Scanner(System.in);
try {
smtpSocket = new Socket("localhost", 55);
os = new DataOutputStream(smtpSocket.getOutputStream());
is = new DataInputStream(smtpSocket.getInputStream());
} catch (UnknownHostException e) {
System.err.println("Don't know about host: localhost");
} catch (IOException e) {
System.err.println("Couldn't get I/O for the connection to: localhost");
}
int choice=2;//rand.nextInt(2);
if(choice==1){
int num=is.read();
System.out.println(num);
}
else if(choice==2){
try {
do{
number=rand.nextInt(911);
// System.out.println(number);
os.writeInt(number);
}while(number!=100);
os.close();
is.close();
smtpSocket.close();
} catch (UnknownHostException e) {
System.err.println("Trying to connect to unknown host: " + e);
} catch (IOException e) {
System.err.println("IOException: " + e);
}
}
}
}