suppose we use the following classes to illustrate a client and a server :
Client
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.PrintWriter;
import java.net.Socket;
import java.util.Scanner;
public class Client {
private PrintWriter toServer;
private BufferedReader fromServer;
private Socket socket;
public Client() throws IOException {
socket = new Socket("127.0.0.1", 3000);
}
public void openStreams() throws IOException {
toServer = new PrintWriter(socket.getOutputStream(), true);
fromServer = new BufferedReader(new InputStreamReader(
socket.getInputStream()));
}
public void closeStreams() throws IOException {
fromServer.close();
toServer.close();
socket.close();
}
public void run() throws IOException {
openStreams();
String msg = "";
Scanner scanner = new Scanner(System.in);
toServer.println("Hello from Client.");
while (!"exit".equals(msg)) {
System.out.println(">");
toServer.println("msg");
String tmp = fromServer.readLine();
System.out.println("Server said: " + tmp);
}
closeStreams();
}
}
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 myServer {
private static ServerSocket serverSocket;
private static Socket socket;
private static PrintWriter toClient;
private static BufferedReader fromClient;
public static void run() throws IOException {
System.out.println("Server is waiting for connections...");
while (true) {
openStreams();
processClient();
closeStreams();
}
}
public static void openStreams() throws IOException {
serverSocket = new ServerSocket(3000);
socket = serverSocket.accept();
toClient = new PrintWriter(socket.getOutputStream(), true);
fromClient = new BufferedReader(new InputStreamReader(
socket.getInputStream()));
}
public static void closeStreams() throws IOException {
fromClient.close();
toClient.close();
socket.close();
serverSocket.close();
}
public static void processClient() throws IOException {
System.out.println("Connection established.");
String msg = fromClient.readLine();
toClient.println("Client said " + msg);
}
}
if , we run the server first and then after server is ready, we run the client, we would get the following error:
Error in Client Software caused connection abort: recv failed
what is the problem?
Be careful about your code
while (true){
openStreams();
processClient();
closeStreams();
}
In this case, the socket connection has always been reset. As a result, the Client cannot create the socket connection successfully.
You should let you code be like:
openStreams();
while(someCondition){
processClient();
}
closeStream();
maybe you can try to use older version of java, similar thing happened to me and when i used sdk 1.6 instead of 1.7 everything fixed
Related
My client can send a single request to the server. I want to create some loads by looping the client 20 times, and having 5 clients running. I tried something based on this post, but it didn't work.
My Server
import java.io.*;
import java.net.*;
import java.util.ArrayList;
import java.util.Random;
public class MyServer {
public static void main(String[] args) throws IOException {
String jokes[] = {"j1", "j2", "j3"};
ServerSocket socket = new ServerSocket(9000);
while(true){
Socket s = socket.accept();
PrintWriter print = new PrintWriter(s.getOutputStream(), true);
String ip = (InetAddress.getLocalHost().getHostAddress());
print.println(ip+jokes[(int)(Math.random()*(jokes.length-1))]);
s.close();
print.close();
}
}
}
My Client
import java.io.*;
import java.net.*;
public class MyClient{
public static void main(String[]args) throws IOException{
System.out.println(args[0]);
System.out.println(args[1]);
Socket socket = new Socket(args[0], Integer.parseInt(args[1]));
BufferedReader in = new BufferedReader(new InputStreamReader(socket.getInputStream()));
String message;
while((message = in.readLine()) != null)
{
System.out.println(message);
System.out.println(cnt);
}
socket.close();
}
}
I'm not familiar with java networking programming, any suggestions would be great.
I looped the client 20 times and opened 5 terminals.
import java.io.*;
import java.net.*;
public class MyClient{
public static void main(String[]args) throws IOException{
System.out.println(args[0]);
System.out.println(args[1]);
int cnt = 0;
while(cnt<20) {
Socket socket = new Socket(args[0], Integer.parseInt(args[1]));
BufferedReader in = new BufferedReader(new InputStreamReader(socket.getInputStream()));
String message;
while((message = in.readLine()) != null)
{
System.out.println(message);
System.out.println(cnt);
}
socket.close();
}
}
}
I am trying to write a program, where Client is sending a string to a Server using output stream. Server would see what string it is, it compares it to a conditional, and then sends it back to the client and displays a message on client's side. I would like to understand how it works, and what is wrong with my code so far. Once I get it I will implement it with JavaFX.
Client
import java.io.DataInputStream;
import java.io.DataOutputStream;
import java.io.IOException;
import java.net.Socket;
public class MyClient {
static Socket socket;
static int clientNo;
static DataOutputStream toServer;
static DataInputStream fromServer;
public static void main(String[] args) {
try{
socket = new Socket("localhost", 8888);
System.out.println("Client connected to the server");
fromServer = new DataInputStream(socket.getInputStream());
toServer = new DataOutputStream(socket.getOutputStream());
toServer.writeBytes("listAll");
toServer.flush();
System.out.println("Sending string to the ServerSocket");
} catch (IOException ex) {
System.err.println(ex.getMessage());
}
}
}
Server
import java.io.IOException;
import java.net.ServerSocket;
import java.net.Socket;
import java.util.Date;
public class MyServer {
static final int PORT = 8888;
static ServerSocket serverSocket;
static Socket socket;
public static void main(String[] args) {
try {
serverSocket = new ServerSocket(PORT);
System.out.println("Server started at " + new Date());
System.out.println("Server on PORT: " + PORT + " is open");
System.out.println("Server is ready for multiple clients!");
System.out.println("Waiting for request...");
while(true){
socket = MyServer.serverSocket.accept();
new Thread(new HandleClient(MyClient.socket)).start();
}
} catch (IOException ex) {
System.err.println("Server Error: " + ex.getMessage());
}
}
}
Thread
import java.io.DataInputStream;
import java.io.DataOutputStream;
import java.io.IOException;
import java.net.Socket;
public class HandleClient implements Runnable {
private Socket socket;
public static int clientNo = 1;
public static int condition;
static DataInputStream input ;
static DataOutputStream output;
static String message;
public HandleClient(Socket socket) {
this.socket = socket;
}
#Override
public void run() {
switch (condition) {
case 1:
break;
case 2:
System.out.println("list all");
break;
case 3:
break;
default:
System.out.println("Client #" + clientNo + " connected!");
clientNo++;
try {
input = new DataInputStream(socket.getInputStream());
output = new DataOutputStream(socket.getOutputStream());
message = input.readUTF();
System.out.println(message);
if("listAll".equals(message)){
HandleClient.condition = 2;
new Thread(new HandleClient(socket)).start();
}
} catch (IOException ex) {
System.err.println("One of the clients disconnected");
}
break;
}
}
}
I really appreciate any help! I understand I might have some code missing to send the response back to the client? Please let me know if the direction I am going is good.
I am trying to write the Client class of this EchoServer so that the server can echo my input. It seems that the EchoServer can only read the client's inputs and print it without echoing it again.
Here's the EchoServer class.
import java.io.IOException;
import java.io.PrintWriter;
import java.net.ServerSocket;
import java.net.Socket;
import java.util.Scanner;
public class EchoServer implements Runnable {
Socket socket;
public EchoServer(Socket socket) {
this.socket = socket;
}
public void run() {
System.out.printf("connection received from %s\n", socket);
try {
PrintWriter pw = new PrintWriter(socket.getOutputStream());
Scanner in = new Scanner(socket.getInputStream());
while (in.hasNextLine()) {
String line = in.nextLine();
System.out.printf("%s says: %s\n", socket, line);
pw.printf("echo: %s\n", line);
pw.flush();
}
pw.close();
in.close();
} catch (IOException e) {
e.printStackTrace();
}
}
public static void main(String[] args) throws IOException {
ServerSocket serverSocket = new ServerSocket(4343);
System.out.printf("socket open, waiting for connections on %s\n",serverSocket);
while (true) {
Socket socket = serverSocket.accept();
EchoServer server = new EchoServer(socket);
new Thread(server).start();
}
}
}
This is my EchoClient class, it reads the system input and writes it to the socket.
import java.io.*;
import java.net.Socket;
import java.net.UnknownHostException;
import java.util.Scanner;
public class EchoClient {
Socket socket;
private Scanner in;
private PrintWriter out;
public EchoClient(String address, int port) {
try {
socket = new Socket(address, port);
System.out.println("Connected!");
in = new Scanner(System.in);
out = new PrintWriter(socket.getOutputStream());
} catch (UnknownHostException u) {
System.out.println(u);
} catch (IOException e) {
System.out.println(e);
}
String line = "";
while (!line.equals("over")) {
line = in.nextLine();
out.println(line);
}
out.close();
}
public static void main(String[] args) throws IOException {
EchoClient c1 = new EchoClient("127.0.1.1", 4343);
EchoClient c2 = new EchoClient("127.0.1.1", 4343);
}
}
It seems that the Printwriter of EchoServer is not writing the echo statements. I wonder why?
This is my server code:
package ServerSideHammingCodeCheckingAndResponse;
import java.io.BufferedReader;
import java.io.BufferedWriter;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.OutputStreamWriter;
import java.net.ServerSocket;
import java.net.Socket;
public class Server
{
private ServerSocket serverSocket;
private int port;
public Server(int port)
{
this.port = port;
}
public void start() throws IOException
{
System.out.println("Server starts at port:" + port);
serverSocket = new ServerSocket(port);
System.out.println("Waiting for client...");
Socket client = serverSocket.accept();
sendMessage(client, "This is Hamming Code Checking.");
boolean checkInput = false;
String input = null;
while (!checkInput)
{
input = getMessage(client);
if(input.length() == 7 && input.matches("[01]+"))
checkInput = true;
else
sendMessage(client, "invalid");
}
sendMessage(client, input);
}
private void sendMessage(Socket client, String message) throws IOException
{
BufferedWriter writer = new BufferedWriter(new OutputStreamWriter(client.getOutputStream()));
writer.write(message);
writer.flush();
writer.close();
}
private String getMessage(Socket client) throws IOException
{
String userInput;
BufferedReader reader = new BufferedReader(new InputStreamReader(client.getInputStream()));
userInput = reader.readLine();
return userInput;
}
public static void main(String[] args)
{
int portNumber = 9987;
try {
Server socketServer = new Server(portNumber);
socketServer.start();
} catch (IOException e) {
e.printStackTrace();
}
}
}
This is my client code:
package ClientSideDataTransmitter;
import java.io.BufferedReader;
import java.io.BufferedWriter;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.OutputStreamWriter;
import java.net.Socket;
import java.net.UnknownHostException;
import java.util.Scanner;
public class Client
{
private String hostname;
private int port;
Socket socketClient;
public Client(String hostname, int port)
{
this.hostname = hostname;
this.port = port;
}
public void connect() throws UnknownHostException, IOException
{
System.out.println("Attempting to connect to " + hostname + ":" + port);
socketClient = new Socket(hostname, port);
System.out.println("\nConnection Established.");
}
public void readResponse() throws IOException
{
String userInput;
BufferedReader reader = new BufferedReader(new InputStreamReader(socketClient.getInputStream()));
System.out.print("Response from server: ");
while ((userInput = reader.readLine()) != null) {
System.out.println(userInput);
}
}
public void sendData() throws IOException
{
Scanner sc = new Scanner(System.in);
BufferedWriter writer = new BufferedWriter(new OutputStreamWriter(socketClient.getOutputStream()));
System.out.println("Enter a 7-bits binary as message to server:\n");
String input = sc.nextLine();
writer.write(input);
writer.flush();
}
public static void main(String arg[])
{
Client client = new Client ("localhost", 9987);
try {
client.connect();
client.readResponse();
client.sendData();
client.readResponse();
} catch (UnknownHostException e) {
System.err.println("Host unknown. Cannot establish connection");
} catch (IOException e) {
System.err.println("Cannot establish connection. Server may not be up." + e.getMessage());
}
}
}
I havent finish up the code so please ignore minor mistakes in the code.
When I start Server, then Client, and send an input from Client to Server. Server seems not getting the data from Client since I send back that input from server to client to print it out, it prints nothing.
I think there may be problems in the method getMessage() in the server code but I cant fix it. Please help me fix the code. Many thanks!
Server:
Server starting at port 9987
Waiting for client...
Client:
Attempting to connect to localhost:9987
Connection Established.
Response from server: This is Hamming Code Checking.
Enter a 7-bits binary as message to server:
1234567
Response from server:
On top of Shriram suggestions I advise you to use PrintWriter here to avoid closing connection. It's also somewhat more convenient to use. Here's working example:
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 {
private ServerSocket serverSocket;
private int port;
public Server(int port) {
this.port = port;
}
public void start() throws IOException {
System.out.println("Server starts at port:" + port);
serverSocket = new ServerSocket(port);
System.out.println("Waiting for client...");
Socket client = serverSocket.accept();
sendMessage(client, "This is Hamming Code Checking.");
boolean checkInput = false;
String input = null;
while (!checkInput) {
input = getMessage(client);
if (input.length() == 7 && input.matches("[01]+"))
checkInput = true;
else
sendMessage(client, "invalid");
}
sendMessage(client, input);
}
private void sendMessage(Socket client, String message) throws IOException {
PrintWriter writer = new PrintWriter(client.getOutputStream(), true);
writer.println(message);
}
private String getMessage(Socket client) throws IOException {
String userInput;
BufferedReader reader = new BufferedReader(new InputStreamReader(client.getInputStream()));
userInput = reader.readLine();
return userInput;
}
public static void main(String[] args) {
int portNumber = 9987;
try {
Server socketServer = new Server(portNumber);
socketServer.start();
} catch (IOException e) {
e.printStackTrace();
}
}
}
Client:
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.PrintWriter;
import java.net.Socket;
import java.net.UnknownHostException;
import java.util.Scanner;
public class Client {
private String hostname;
private int port;
Socket socketClient;
public Client(String hostname, int port) {
this.hostname = hostname;
this.port = port;
}
public void connect() throws UnknownHostException, IOException {
System.out.println("Attempting to connect to " + hostname + ":" + port);
socketClient = new Socket(hostname, port);
System.out.println("\nConnection Established.");
}
public void readResponse() throws IOException {
String userInput;
BufferedReader reader = new BufferedReader(new InputStreamReader(socketClient.getInputStream()));
System.out.print("Response from server: ");
userInput = reader.readLine();
System.out.println(userInput);
}
public void sendData() throws IOException {
Scanner sc = new Scanner(System.in);
PrintWriter writer = new PrintWriter(socketClient.getOutputStream(), true);
System.out.println("Enter a 7-bits binary as message to server:\n");
String input = sc.nextLine();
writer.println(input);
}
public static void main(String arg[]) {
Client client = new Client("localhost", 9987);
try {
client.connect();
client.readResponse();
client.sendData();
client.readResponse();
} catch (UnknownHostException e) {
System.err.println("Host unknown. Cannot establish connection");
} catch (IOException e) {
System.err.println("Cannot establish connection. Server may not be up." + e.getMessage());
}
}
}
The problem with your code is writer.close() in sendMessage() will internally close the writer objects. Your server program will be closed and no longer in connection to accept the connections.
You're losing data by creating a new BufferedReader per message. You need to use the same one for the life of the socket. Ditto 'PrintWriter` or whatever you use to send.
I am trying to launch server and client thread on the same process, but seems like the server thread is blocking the client thread (or vice versa). I'm not allowed to use any global variable between those threads(like semaphore or mutex, since the client and the server thread are launched by upper-class that I don't have the access of).
I found a similar question here , but it still use two different process (two main function).
Here is a sample of my code
The server code:
public class MyServer implements Runnable{
ServerSocket server;
Socket client;
PrintWriter out;
BufferedReader in;
public MyServer() throws IOException{
server = new ServerSocket(15243, 0, InetAddress.getByName("localhost"));
}
#Override
public void run() {
while(true){
try {
ArrayList<String> toSend = new ArrayList<String>();
System.out.println("I'll wait for the client");
client = server.accept();
out = new PrintWriter(client.getOutputStream(), true);
in = new BufferedReader(new InputStreamReader(client.getInputStream()));
String inputLine;
while((inputLine = in.readLine()) != null){
toSend.add("answering : "+inputLine);
}
for(String resp : toSend){
out.println(resp);
}
client.close();
out.close();
in.close();
} catch (IOException ex) {
}
}
}
}
And the client code:
public class MyClient implements Runnable{
Socket socket;
PrintWriter out;
BufferedReader in;
public MyClient(){
}
#Override
public void run() {
int nbrTry = 0;
while(true){
try {
System.out.println("try number "+nbrTry);
socket = new Socket(InetAddress.getByName("localhost"), 15243);
out = new PrintWriter(socket.getOutputStream(), true);
in = new BufferedReader(new InputStreamReader(socket.getInputStream()));
out.println("Hello "+nbrTry+" !! ");
String inputLine;
while((inputLine = in.readLine()) != null){
System.out.println(inputLine);
}
nbrTry++;
} catch (UnknownHostException ex) {
} catch (IOException ex) {
}
}
}
}
And the supposed upper-class launching those thread:
public class TestIt {
public static void main(String[] argv) throws IOException{
MyServer server = new MyServer();
MyClient client = new MyClient();
(new Thread(server)).start();
(new Thread(client)).start();
}
}
It gives me as output:
I'll wait for the client
Try number 0
And it stuck here. What should I do to keep both server and client code running?
Thank you.
I'll be willing to take up your questions but basically you need to think through your logic a bit more carefully.
MyServer.java
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.PrintWriter;
import java.net.InetAddress;
import java.net.ServerSocket;
import java.net.Socket;
public class MyServer implements Runnable {
ServerSocket server;
public MyServer() throws IOException {
server = new ServerSocket(15243, 0, InetAddress.getByName("localhost"));
}
#Override
public void run() {
while (true) {
try {
// Get a client.
Socket client = server.accept();
// Write to client to tell him you are waiting.
PrintWriter out = new PrintWriter(client.getOutputStream(), true);
out.println("[Server] I'll wait for the client");
// Let user know something is happening.
System.out.println("[Server] I'll wait for the client");
// Read from client.
BufferedReader in = new BufferedReader(new InputStreamReader(client.getInputStream()));
String inputLine = in.readLine();
// Write answer back to client.
out.println("[Server] Answering : " + inputLine);
// Let user know what it sent to client.
System.out.println("[Server] Answering : " + inputLine);
in.close();
out.close();
client.close();
} catch (Exception e) {
}
}
}
}
MyClient.java
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.net.UnknownHostException;
public class MyClient implements Runnable {
Socket socket;
PrintWriter out;
BufferedReader in;
public MyClient() throws UnknownHostException, IOException {
}
#Override
public void run() {
int nbrTry = 0;
while (true) {
try {
// Get a socket
socket = new Socket(InetAddress.getByName("localhost"), 15243);
// Wait till you can read from socket.
in = new BufferedReader(new InputStreamReader(socket.getInputStream()));
String inputLine = in.readLine();
//inputLine contains the text '[Server] I'll wait for the client'. means that server is waiting for us and we should respond.
// Write to socket
out = new PrintWriter(socket.getOutputStream(), true);
out.println("[Client] Hello " + nbrTry + " !! ");
// Let user know you wrote to socket
System.out.println("[Client] Hello " + nbrTry++ + " !! ");
} catch (UnknownHostException ex) {
} catch (IOException ex) {
}
}
}
}
TestIt.java
import java.io.IOException;
public class TestIt {
public static void main(String[] argv) throws IOException {
MyServer server = new MyServer();
MyClient client = new MyClient();
(new Thread(server)).start();
(new Thread(client)).start();
}
}
Your client sends a string, then reads until the stream is exhausted:
while((inputLine = in.readLine()) != null){
BufferedReader.readLine() only returns null at the end of the stream, as I recall. On a stream, it will block until input is available
Your server receives until the stream is exhausted, then sends back its response.
After sending one line, you now have:
Your client waiting for a response.
Your server still waiting for more data from the client. But it doesn't send anything back until the end of the stream from the client (which never happens because the client is waiting for your response).