Problems with MultiClient - server in Java - java

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!

Related

Why my java multicast clientserver chat work with only one client at the time?

as I said, i'm tring to do a chat for sevral clients, and one server in java. However, it seems that only one client at the time can connect on the server, and I really don't know why (i'm a begginer in this field).
I have 4 classes, here are they :
MainClient :
package Multicast;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.PrintWriter;
import java.net.Socket;
import java.net.UnknownHostException;
import java.util.Scanner;
public class MainClient {
public static void main(String[] args) {
try (Socket socket = new Socket("localhost", 5000)){
BufferedReader input = new BufferedReader(new java.io.InputStreamReader(socket.getInputStream()));
PrintWriter output = new PrintWriter(socket.getOutputStream(), true);
Scanner scanner = new Scanner(System.in);
String userInput;
String reponse;
String clientName = "none";
ClientThread clientThread = new ClientThread(socket);
clientThread.start();
do {
if(clientName.equals("none")) {
System.out.println("please enter your name");
userInput = scanner.nextLine();
clientName = userInput;
output.println(userInput);
}
else {
String message = ("|"+clientName +"| :");
//System.out.println(message);
userInput = scanner.nextLine();
output.println(message + " " + userInput);
if (userInput.equals("exit")) {
break;
}
}
}while (!userInput.equals("exit"));
} catch (UnknownHostException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
}
}
ClientThread :
package Multicast;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.net.Socket;
public class ClientThread extends Thread{
private Socket socket;
private BufferedReader input;
public ClientThread(Socket s) throws IOException {
this.socket = s;
this.input = new BufferedReader(new InputStreamReader(socket.getInputStream()));
}
#Override
public void run() {
try {
while(true) {
String reponse = input.readLine();
System.out.println(reponse);
}
}
catch(IOException e){
e.printStackTrace();
}
finally {
try {
input.close();
}
catch(Exception e) {
e.printStackTrace();
}
}
}
}
MainServer :
package Multicast;
import java.io.IOException;
import java.net.ServerSocket;
import java.net.Socket;
import java.util.ArrayList;
public class MainServeur {
public static void main(String[] args) {
ArrayList<ServerThread> threadList = new ArrayList<>();
try(ServerSocket serverSocket = new ServerSocket(5000)){
Socket socket = serverSocket.accept();
ServerThread serverThread= new ServerThread(socket, threadList);
threadList.add(serverThread);
serverThread.start();
} catch (IOException e) {
e.printStackTrace();
}
}
}
and ServerThread :
package Multicast;
import java.io.BufferedReader;
import java.io.InputStreamReader;
import java.io.PrintWriter;
import java.net.Socket;
import java.util.ArrayList;
public class ServerThread extends Thread{
private Socket socket;
private ArrayList<ServerThread> threadList;
private PrintWriter output;
public ServerThread(Socket socket, ArrayList<ServerThread> threads) {
this.socket = socket;
this.threadList = threads;
}
#Override
public void run() {
try {
BufferedReader input = new BufferedReader(new InputStreamReader(socket.getInputStream()));
output = new PrintWriter(socket.getOutputStream(), true);
while(true) {
String outputString = input.readLine();
if(outputString.equals("exit")) {
break;
}
printToAllClients(outputString);
System.out.println("Server received : " + outputString);
}
}
catch(Exception e) {
System.out.println("error occured in main of server : "+ e.getStackTrace());
}
}
private void printToAllClients(String outputString) {
for(ServerThread sT : threadList) {
sT.output.println(outputString);
}
}
}
when i try to connect a second client, this error occurs :
java.net.BindException: Cannot assign requested address: connect
at java.base/sun.nio.ch.Net.connect0(Native Method)
at java.base/sun.nio.ch.Net.connect(Net.java:579)
at java.base/sun.nio.ch.Net.connect(Net.java:568)
at java.base/sun.nio.ch.NioSocketImpl.connect(NioSocketImpl.java:588)
at java.base/java.net.SocksSocketImpl.connect(SocksSocketImpl.java:327)
at java.base/java.net.Socket.connect(Socket.java:633)
at java.base/java.net.Socket.connect(Socket.java:583)
at java.base/java.net.Socket.<init>(Socket.java:507)
at java.base/java.net.Socket.<init>(Socket.java:287)
at Multicast.MainClient.main(MainClient.java:13)
I followed this tutorial, thanks a lot and sorry if the post is too long.
Edit : My problem is solved, here are the changes :
package Multicast;
import java.io.IOException;
import java.net.ServerSocket;
import java.net.Socket;
import java.util.ArrayList;
public class MainServeur {
public static void main(String[] args) {
ArrayList<ServerThread> MyThread = new ArrayList<>();
try (ServerSocket serverSocket = new ServerSocket(5000)) {
for (;;) {
Socket socket = serverSocket.accept();
ServerThread s = new ServerThread(socket, MyThread);
MyThread.add(s);
s.start();
}
} catch (IOException e) {
e.printStackTrace();;
}
}
}
You should have one ServerSocket that accepts one client after another in a loop,
on the specified port 5000.
The session then is handled in an other thread, so the next client can be accepted (waited upon).
public class MainServeur {
public static void main(String[] args) {
try (ServerSocket serverSocket = new ServerSocket(5000)) {
for (;;) {
Socket socket = serverSocket.accept();
new ServerThread(socket).start();
}
} catch (IOException e) {
System.getLogger(MainServeur.class.getName()).error(e);
}
}
}
Rather than elementary using a Thread, you can use ExecutorServices.
ThreadPoolExecutor executor = (ThreadPoolExecutor) executors.newFixedThreadPool(50);
That goes beyond the question asked, but allows thread pools limiting the number of clients, wait for all threads to end and more.

Application chat Client Server - cant send the second message

I'm writing a Client-Server chat application. I can connect them and I can send-receive the first message. But I can't send the second one. I tried to add the do...while() statement for a repetition but It doesn't work. Could some one help me to resolve this problem? Many thanks
This is my server class
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.OutputStreamWriter;
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 {
ServerSocket server = new ServerSocket(4999);
Socket serverSocket = server.accept();
System.out.println("client is connected");
String messIn = "", messOut = "";
InputStreamReader serverInput = new InputStreamReader(serverSocket.getInputStream());
BufferedReader serverBufIn = new BufferedReader(serverInput);
Scanner serverScanner = new Scanner(System.in);
PrintWriter serverWriter = new PrintWriter(serverSocket.getOutputStream());
do {
messIn = serverBufIn.readLine();
System.out.println("client : " + messIn);
messOut = serverScanner.nextLine();
serverWriter.print(messOut);
serverWriter.flush();
} while (messOut.equals("quit"));
serverSocket.close();
serverWriter.close();
}
}`
This my client class
`import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.PrintWriter;
import java.net.InetAddress;
import java.net.Socket;
import java.util.Scanner;
public class client {
public static void main(String[] args) throws IOException {
Socket clientSocket = new Socket(InetAddress.getLocalHost(), 4999);
System.out.println("You are connected. Say something!");
String messIn = "", messOut = "";
InputStreamReader clientInput = new InputStreamReader(clientSocket.getInputStream());
BufferedReader clientBufIn = new BufferedReader(clientInput);
Scanner clientScanner = new Scanner(System.in);
PrintWriter clientWriter = new PrintWriter(clientSocket.getOutputStream());
do {
messOut = clientScanner.nextLine();
clientWriter.println(messOut);
clientWriter.flush();
messIn = clientBufIn.readLine();
System.out.println("server : " + messIn);
} while (messOut.equals("quit"));
clientSocket.close();
clientWriter.close();
}
}
`
try while (true) { }
my code:
public static void newSocket(int port) throws IOException {
ServerSocket ss = new ServerSocket(port);
while (run) {
try {
final Socket socket = ss.accept();
new Thread() {
public void run() {
try {
while (true) {
int i = socket.getInputStream().available();
if (i > 0) {
byte[] bytes = new byte[i];
socket.getInputStream().read(bytes, 0, i);
String s = new String(bytes);
String[] split = s.split("\\|");
if (split.length > 1) {
if (split[0].equals("hello")) {
String msg = split[1];
System.out.println(msg);
PrintStream p = new PrintStream(socket.getOutputStream());
p.println("hello back");
}
}
}
}
} catch (Exception e) {
e.printStackTrace();
}
}
}.start();
} catch (Exception e) {
e.printStackTrace();
}
}
ss.close();
}

Java - Multi-Threaded Socket Server, How to check a clients connection to the server?

I am wondering how to check if a client is still connected to a server, like to see if the client has crashed, and if not, to check its ping to the server. Im adding all new clients to an ArrayList and when they crash I want to know how to remove them from the list so that I can keep things clean. Im not sure how to do this with Synchronization or if thats possible. If there is a better way too control my threads any advice is welcomed, thanks.
SERVER CODE:
package Main;
import java.io.IOException;
import java.io.PrintStream;
import java.net.ServerSocket;
import java.net.Socket;
import java.util.ArrayList;
import java.util.List;
public class MultiThreadedServer implements Runnable{
private static List<Thread> clients = new ArrayList<Thread>();
Socket cs;
private static ServerSocket ss;
private static int port = 25570;
MultiThreadedServer(Socket cs){
this.cs = cs;
}
public static void main(String args[]) throws Exception{
try{
ss = new ServerSocket(port);
System.out.println("Server Listening");
}catch(IOException e){
System.out.println("Port Taken");
}
while(true){
Socket newClient = ss.accept();
System.out.println(newClient.getInetAddress() + " Has Connected");
Thread client = new Thread(new MultiThreadedServer(newClient));
client.start();
clients.add(client);
System.out.println("Connected Clients: " + clients.size());
}
}
public void run(){
try{
PrintStream ps = new PrintStream(cs.getOutputStream());
ps.println("Welcome Client #" + clients.size());
}catch(IOException e){
System.out.println(e);
}
}
}
CLIENT CODE:
package Main;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.OutputStreamWriter;
import java.io.PrintWriter;
import java.net.Socket;
import java.net.UnknownHostException;
public class Client{
private static String ip = "127.0.0.1";
private static int port = 25570;
public static void main(){
Socket socket;
BufferedReader reader;
PrintWriter writer;
try {
socket = new Socket(ip,port);
BufferedReader in = new BufferedReader(new
InputStreamReader(socket.getInputStream()));
OutputStreamWriter os = new
OutputStreamWriter(socket.getOutputStream());
PrintWriter out = new PrintWriter(os);
System.out.println(in.readLine());
} catch (UnknownHostException e) {
System.out.println("ERROR UNKNOWN");
e.printStackTrace();
} catch (IOException e) {
System.out.println("Could not connect to server!");
e.printStackTrace();
return;
}
}
}

Java Why does the server not respond to a second client?

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();
}
}
}
}
}

server make a txt file and client write it

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);
}
}
}
}

Categories