server code :
public class server {
//private static ArrayList<user> t = new ArrayList<>();
public static Socket s = null;
public static ServerSocket ss = null;
public static void main(String[] args) {
try {
ss = new ServerSocket(1777);
while (true) {
System.out.println("waiting for connexion");
s = ss.accept();
System.out.println("connected with "+s.getRemoteSocketAddress());
InputStream is = s.getInputStream();
OutputStream os = s.getOutputStream();
InputStreamReader isr = new InputStreamReader(is);
BufferedReader br = new BufferedReader(isr);
PrintWriter pw = new PrintWriter(os,true);
String username = br.readLine();
int number = 0;
user us = new user(s,number,username);
//t.add(us);
pw.print(us);
//new service(s,username,number,t).start();
new service(s,us).start();
number++;
}
} catch (Exception e) {
System.out.println(e.getMessage());
}
}
}
service class code :
public class service extends Thread {
private static Socket s;
private static String user;
private static int number ;
private ArrayList<user> locallist = new ArrayList<user>();
private static user us;
public service(Socket s,user u){
this.s = s;
this.us = u;
locallist.add(u);
}
#Override
public void run() {
int listsize = locallist.size();
user lastuser = locallist.get(listsize-1);
try {
while (true) {
InputStream is = s.getInputStream();
OutputStream os = s.getOutputStream();
InputStreamReader isr = new InputStreamReader(is);
BufferedReader br = new BufferedReader(isr);
PrintWriter pw = new PrintWriter(os,true);
System.out.println("last user : " + lastuser);
}
} catch (Exception e) {
e.printStackTrace();
}
}
}
client class code :
public class client {
public static void main(String[] args) {
try {
while (true) {
Socket s = new Socket("localhost",1777);
System.out.println("connected with localhost");
InputStream is = s.getInputStream();
OutputStream os = s.getOutputStream();
InputStreamReader isr = new InputStreamReader(is);
BufferedReader br = new BufferedReader(isr);
PrintWriter pw = new PrintWriter(os,true);
Scanner e = new Scanner(System.in);
System.out.println("enter you username to continue");
String username = e.next();
pw.println(username);
}
} catch (Exception ex) {
ex.printStackTrace();
}
}
}
the server output :
waiting for connexion
connected with /127.0.0.1:51899
waiting for connexion
connected with /127.0.0.1:51902
last user : username teste usernumber 0
last user : username teste usernumber 0
last user : username teste usernumber 0
basically infinit loop
the client output :
connected with localhost
enter you username to continue
teste
connected with localhost
enter you username to continue
my question is how can i stop the infinit loop and display the last connected/added member after each client connection
in the server class:
public static void main(String[] args) {
try {
ss = new ServerSocket(1777);
int number = 0; // <--- place the counter here not in the while
while (true) {
System.out.println("waiting for connexion");
s = ss.accept();
System.out.println("connected with "+s.getRemoteSocketAddress());
InputStream is = s.getInputStream();
OutputStream os = s.getOutputStream();
InputStreamReader isr = new InputStreamReader(is);
BufferedReader br = new BufferedReader(isr);
PrintWriter pw = new PrintWriter(os,true);
String username = br.readLine();
//int number = 0; // Not here ... you just set the counter always to 0
user us = new user(s,number,username);
pw.print(us);
new service(s,us).start();
number++;
}
} catch (Exception e) {
System.out.println(e.getMessage());
}
}
in the service class:
#Override
public void run() {
int listsize = locallist.size();
user lastuser = locallist.get(listsize-1);
try {
// while(true) { // <--- should be removed
InputStream is = s.getInputStream();
OutputStream os = s.getOutputStream();
InputStreamReader isr = new InputStreamReader(is);
BufferedReader br = new BufferedReader(isr);
PrintWriter pw = new PrintWriter(os,true);
System.out.println("last user : " + lastuser);
// } <--- while-end
// <--- for later use?
} catch (Exception e) {
e.printStackTrace();
}
}
so that is the finished code ... you just had to remove the while in the service-class, move the declaration of the counter-variable "number" out of the while in the server-class.
If you want to use the while in the service-class later for communication between server and client you just have to place a while after you printed the user out.
Related
I am creating a chat program between a server and a client but is run by a main function file.
If "-l" is present on the command line, it will run as a server, otherwise it will run as a client
Command line arguments to run server:
java DirectMessengerCombined -l 3000
Command line arguments to run client:
java DirectMessengerCombined 3000
All three files need to be able to access String args[] in the main function file because that is how it gets the port number
Right now the program is able to send and receive one message at a time successfully (see screenshot)
What changes can I make to the code that will allow me to send and receive multiple messages? (probably involves the use of java threads)
Code of main function file:
import java.io.IOException;
public class MainThread
{
public static void main(String[] args) throws IOException
{
DirectMessengerClient client1 = null;
DirectMessengerServer server1 = null;
for (int i = 0; i < args.length; i++)
{
if (args.length == 1)
{
client1 = new DirectMessengerClient(args);
client1.ClientRun(args);
}
else if (args.length == 2)
{
server1 = new DirectMessengerServer(args);
server1.ServerRun(args);
}
i=args.length + 20;
}
}
}
Code of Server File:
import java.io.*;
import java.net.*;
import java.util.*;
import javax.imageio.IIOException;
public class ServerThread
{
private String[] serverArgs;
public Socket socket;
public boolean keepRunning = true;
int ConnectOnce = 0;
public ServerThread(String[] args) throws IOException
{
// set the instance variable
this.serverArgs = args;
run();
}
public String[] ServerRun(String[] args) throws IOException
{
serverArgs = args;
serverArgs = Arrays.copyOf(args, args.length);
return serverArgs;
}
//run method of ServerRecieve
public void run() throws IOException
{
try
{
if(ConnectOnce == 0)
{
int port_number1 = Integer.valueOf(serverArgs[1]);
ServerSocket serverSocket = new ServerSocket(port_number1);
socket = serverSocket.accept();
ConnectOnce = 4;
}
while(keepRunning)
{
//Reading the message from the client
//BufferedReader br = new BufferedReader(new InputStreamReader(socket.getInputStream()));
InputStream is = socket.getInputStream();
InputStreamReader isr = new InputStreamReader(is);
BufferedReader br = new BufferedReader(isr);
String MessageFromClient = br.readLine();
System.out.println("Message received from client: "+ MessageFromClient);
// ServerSend.start();
runSend();
}
}
catch (IOException e)
{
// TODO Auto-generated catch block
e.printStackTrace();
}
finally
{
}
}
//Run method of ServerSend
public void runSend()
{
while(keepRunning)
{
System.out.println("Server sending thread is now running");
try
{
//Send the message to the server
OutputStream os = socket.getOutputStream();
OutputStreamWriter osw = new OutputStreamWriter(os);
BufferedWriter bw = new BufferedWriter(osw);
//creating message to send from standard input
String newmessage = "";
try
{
// input the message from standard input
BufferedReader input= new BufferedReader(
new InputStreamReader(System.in));
String line = "";
line= input.readLine();
newmessage += line + " ";
}
catch ( Exception e )
{
System.out.println( e.getMessage() );
}
String sendMessage = newmessage;
bw.write(sendMessage + "\n");
bw.flush();
System.out.println("Message sent to client: "+sendMessage);
run();
}
catch (IOException e)
{
// TODO Auto-generated catch block
e.printStackTrace();
}
finally
{
}
}
}
}
Code of Client file:
import java.io.*;
import java.net.*;
import java.util.*;
import static java.nio.charset.StandardCharsets.*;
public class ClientThread implements Runnable
{
int ConnectOnce = 0;
private String[] clientArgs; // <-- added variable
private static Socket socket;
public boolean keepRunning = true;
public ClientThread(String[] args) throws IOException
{
// set the instance variable
this.clientArgs = args;
run(args);
}
public String[] ClientRun(String[] args)
{
clientArgs = args;
clientArgs = Arrays.copyOf(args, args.length);
return clientArgs;
}
public void run(String args[]) throws IOException
{
System.out.println("Client send thread is now running");
while(keepRunning)
{
if(ConnectOnce == 0)
{
String port_number1= args[0];
System.out.println("Port number is: " + port_number1);
int port = Integer.valueOf(port_number1);
String host = "localhost";
InetAddress address = InetAddress.getByName(host);
socket = new Socket(address, port);
ConnectOnce = 4;
}
//Send the message to the server
OutputStream os = socket.getOutputStream();
OutputStreamWriter osw = new OutputStreamWriter(os);
BufferedWriter bw = new BufferedWriter(osw);
//creating message to send from standard input
String newmessage = "";
try
{
// input the message from standard input
BufferedReader input= new BufferedReader(new InputStreamReader(System.in));
String line = "";
line= input.readLine();
newmessage += line + " ";
}
catch (Exception e)
{
System.out.println(e.getMessage());
}
String sendMessage = newmessage;
bw.write(sendMessage + "\n");
bw.flush();
System.out.println("Message sent to server: "+sendMessage);
runClientRead(args);
}
}
public void runClientRead(String args[]) throws IOException
{
System.out.println("Client recieve/read thread is now running");
//Integer port= Integer.valueOf(args[0]);
//String host = "localhost";
//InetAddress address = InetAddress.getByName(host);
//socket = new Socket(address, port);
//Get the return message from the server
InputStream is = socket.getInputStream();
InputStreamReader isr = new InputStreamReader(is);
BufferedReader br = new BufferedReader(isr);
String MessageFromServer = br.readLine();
System.out.println("Message received from server: " + MessageFromServer);
}
#Override
public void run()
{
// TODO Auto-generated method stub
}
}
Currently I can only send and receive one line of text at a time, what changes can I make to the code that will allow me to send and receive multiple messages?
Below is client and server program that I wrote. Now I am confused how to send ack/nack in my program.
I saw few answers on stackoverflow but i am still confused. Can you give an example of ACK/NACK in TCP protocol using java
Client:
public class Client {
public static void main(String args[]) {
try {
Socket client = new Socket("localhost", 2222);
PrintWriter pw = new PrintWriter(client.getOutputStream(), true);
Scanner input = new Scanner(System.in);
boolean a = true;
while (a) {
//receving
BufferedReader br = new BufferedReader(new InputStreamReader(client.getInputStream()));
System.out.println(br.readLine());
if (input.equals("q")) {
a = false;
client.close();
}
pw.println("Client0: " + input.nextLine());
System.out.println(pw);
// System.out.println("Request sent successfully");
}
} catch (Exception ex) {
System.out.println(ex);
}
}
}
Server:
public class Server {
public static void main(String args[]) {
try {
ServerSocket ss = new ServerSocket(2222);
System.out.println("Waiting for client request");
Socket client = ss.accept();
System.out.println("Accepted connection request");
Scanner input = new Scanner(System.in);
while (true) {
// receving
InputStreamReader isr = new InputStreamReader(client.getInputStream());
BufferedReader br = new BufferedReader(isr);
String str = br.readLine();
// sending
PrintStream ps = new PrintStream(client.getOutputStream());
ps.println("Server1: " + input.nextLine());
System.out.println(ps);
}
} catch (Exception e) {
System.out.println(e);
}
}
}
Thank you
I'm delving into sockets for the first time.
The point of the project is for the client to be able to get access to a contact list (CSV) in the server by writing "getall" and exit the program through just that command ("Exit").
The problem is that the client can only write the command and receive the list once and then the server doesn't respond to the client's input anymore.
Here is the socket code for the server and client respectively:
Server:
public class CatalogueServer extends CatalogueLoader {
ServerSocket serverSocket;
ArrayList<CatalogueEntry> catalogue;
public void startServer(int port, String catalogueFile) {
catalogue = loadLocalCatalogue(catalogueFile);
try {
serverSocket = new ServerSocket(port);
while (true) {
Socket clientSocket = serverSocket.accept();
new Thread(
new Runnable() {
public void run() {
try {
InputStream inputStream = clientSocket.getInputStream();
InputStreamReader inputStreamReader = new InputStreamReader(inputStream, "UTF-8");
BufferedReader BR = new BufferedReader(inputStreamReader);
OutputStream outputStream = clientSocket.getOutputStream();
PrintWriter PW = new PrintWriter(outputStream);
String clientInput;
while ((clientInput = BR.readLine()) != null) {
System.out.println(clientInput);
if (clientInput.equals("getall")) {
System.out.println(printCatalogue(catalogue));
PW.println(printCatalogue(catalogue));
PW.flush();
break;
} else if (clientInput.equals("exit")) {
clientSocket.close();
BR.close();
PW.close();
break;
} else {
PW.flush();
break;
}
}
PW.close();
} catch (Exception e) {
e.printStackTrace();
}
}
}
).start();
}
} catch (Exception i) {
i.printStackTrace();
}
}
}
Client:
public class TestClient {
public static void main(String[] args) {
try {
Socket socket = new Socket("localhost", 5253);
OutputStream outputStream = socket.getOutputStream();
InputStream inputStream = socket.getInputStream();
InputStreamReader inputStreamReader = new InputStreamReader(inputStream);
BufferedReader BR = new BufferedReader(inputStreamReader);
while (true) {
String clientInput;
String serverFeedback;
PrintWriter PW = new PrintWriter(outputStream);
Scanner inputScan = new Scanner(System.in, "UTF-8");
clientInput = inputScan.nextLine();
PW.println(clientInput);
PW.flush();
while ((serverFeedback = BR.readLine()) != null) {
System.out.println(serverFeedback);
}
if (clientInput.equals("exit")) {
PW.close();
socket.close();
break;
}
PW.close();
}
}
catch (IOException e){
e.printStackTrace();
}
}
}
I have tried alternating the position and renewal of the readers and writers. But I'm uncertain of where exactly the problem starts.
When you do
while ((serverFeedback = BR.readLine()) != null) {
System.out.println(serverFeedback);
}
You are reading until you reach the end of the stream, i.e. until there is nothing left. As such there is nothing after this.
If you want to reuse the connection, you have to write the code which doesn't use this pattern and only reads until it should stop reading.
public class JavaApplication15 {
public static String ip="127.0.0.1";
public static int port=5060;
public static void main(String[] args) throws IOException {
ServerSocket ss = null;
InetAddress ii = InetAddress.getLocalHost();
System.out.println(ii);
InetAddress ad = InetAddress.getByName(ip);
System.out.println(ad);
InetAddress i = ad;
System.out.println(i);
try {
// TODO code application logic here
ss = new ServerSocket();
ss.bind(new InetSocketAddress(ip, port));
InetSocketAddress ia;
String st=ss.getLocalSocketAddress().toString(); // print socket ip and address
System.out.println(st);
System.out.println("created");
} catch (IOException ex) {
System.out.println("not created");
}
Socket client = null,ee = null;
client = ss.accept();
PrintWriter out = null;
BufferedReader in = null ;
out = new PrintWriter(client.getOutputStream(),true);
in = new BufferedReader(new InputStreamReader(client.getInputStream()));
BufferedReader stdin = new BufferedReader(new InputStreamReader(System.in));
String input = null;
while((input = in.readLine())!=null){
System.out.println(input);
System.out.println("echo :" +in.readLine());
}
out.flush();
in.close();
stdin.close();
client.close();
ss.close();
}
}
}
In this code server is being created and trying to establish a connection with socket. I think this code should show output but it is not showing. For example: if i say hello in the console , it should print hello. But it is not doing that. Can anyone help me what is actually going on here ???
I am trying to read a file from server and able to do it successfully. However, at the client end the statement after the while loop does not execute at all. Kindly help me with this request. The line asking for client input does not show up at all. Please help
//Client Side Code
import java.io.*;
import java.net.*;
import java.util.StringTokenizer;
import java.lang.*;
public class oss_client1 {
public static void main(String args[]) throws Exception {
Socket sock = new Socket("127.0.0.1", 2222);
char n1;
int choice;
// reading the file name from keyboard. Uses input stream
BufferedReader keyRead = new BufferedReader(new InputStreamReader(
System.in));
BufferedReader dis = new BufferedReader(
new InputStreamReader(System.in));
// receiving the contents from server. Uses input stream
InputStream istream = sock.getInputStream();
InputStream istream1 = sock.getInputStream();
// sending the file name to server. Uses PrintWriter
OutputStream ostream = sock.getOutputStream();
BufferedReader dRead = new BufferedReader(
new InputStreamReader(istream));
BufferedReader socketRead = new BufferedReader(new InputStreamReader(
istream1));
PrintWriter pwrite = new PrintWriter(ostream, true);
PrintWriter pwrite1 = new PrintWriter(ostream, true);
do {
System.out.println("Enter the website name: ");
String u_input = keyRead.readLine();
pwrite.println(u_input);
String str;
while ((str = dRead.readLine()) != null) {
// reading line-by-line
System.out.println(str);
}
str = dRead.readLine();
System.out.println(str);
dRead.close();
System.out
.print("\nPlease enter the product code which you want to buy: ");
String pcode = dis.readLine();
pwrite1.println(pcode);
String pcode_res = socketRead.readLine();
System.out.print("\nBack from server " + pcode_res + "\n");
System.out.println("\nDo you want to continue(Y/N)");
String n = dis.readLine();
n1 = n.charAt(0);
} while (n1 == 'Y' || n1 == 'y');
pwrite.close();
socketRead.close();
keyRead.close();
}
}
//Server side code
import java.net.*;
import java.util.*;
import java.io.*;
public class oss_server1 {
static Socket clientSocket = null;
static ServerSocket serverSocket = null;
static clientThread t[] = new clientThread[10];
public static void main(String args[]) throws Exception {
int port_number = 2222; // The default port
if (args.length < 1) {
System.out.println("Now using port number=" + port_number);
} else {
port_number = Integer.valueOf(args[0]).intValue();
}
/* Try to open a server socket on port port_number (default 2222) */
try {
serverSocket = new ServerSocket(port_number);
} catch (IOException e) {
System.out.println(e);
}
while (true) {
try {
clientSocket = serverSocket.accept();
for (int i = 0; i <= 9; i++) {
if (t[i] == null) {
(t[i] = new clientThread(clientSocket, t)).start();
port_number++;
break;
} // end of if loop
} // end for looop
}// end of try loop
catch (IOException e) {
System.out.println(e);
}
} // end of while loop
}
}
class clientThread extends Thread {
DataInputStream is = null;
DataOutputStream dout = null;
Socket clientSocket = null;
clientThread t[];
public clientThread(Socket clientSocket, clientThread[] t) {
this.clientSocket = clientSocket;
this.t = t;
}
public void run() {
try {
System.out.println("Welcome to US ONLINE SHOPPING SYSTEM");
String website = "www.US_OSS.com";
// buffer stream for reading the choice from client
InputStream istream = clientSocket.getInputStream();
InputStream istream1 = clientSocket.getInputStream();
BufferedReader webRead = new BufferedReader(new InputStreamReader(istream));
BufferedReader pcodeRead = new BufferedReader(new InputStreamReader(istream));
// buffer stream reading the file contents
BufferedReader displayRead = new BufferedReader(new FileReader(
"display_client.txt"));
BufferedReader prodRead = new BufferedReader(new FileReader(
"product_list.txt"));
// keeping output stream ready to send the contents
OutputStream ostream = clientSocket.getOutputStream();
PrintWriter pwrite = new PrintWriter(ostream, true);
String str, str1, pcode;
String fname = webRead.readLine();
if (fname.compareTo(website) != 0) {
pwrite.println("Error 404: NOT FOUND");
} else {
while ((str = displayRead.readLine()) != null) // reading line-by-line from file
{
pwrite.println(str);
}
displayRead.close();
str = "END OF PRODUCT LIST";
pwrite.println(str);
pcode = pcodeRead.readLine();
System.out.print("\nReceived PCODE is: " + pcode);
pwrite.println(pcode);
}
// pwrite.close();
} // end of try block
catch (IOException e) {
System.out.println(e);
}
} // end of run class
}// end of Client thread class
BufferedReader when reading after EOF will issue IOException
Instead I suggest you use Scanner to read files
Your code would look like...(in ServerSide)
Scanner scnFile=new Scanner(new File("display_client.txt")); //give absolute path if necessary
while(scnFile.hasNext()){
System.out.println(scnFile.nextLine());
}
scnFile.close();