Im flabbergasted.
I took code from https://docs.oracle.com/javase/tutorial/networking/sockets/examples/EchoServer.java
for the server. And
https://docs.oracle.com/javase/tutorial/networking/sockets/examples/EchoClient.java
for the Client. I made minor changes. Mostly so that there is no back and forth echoing. Rather the Server should constantly with 2 second delays send same string. But I just cant understand why the client isnt working.
It sends the Exception message:
Couldn't get I/O for the connection to 127.0.0.1
I run the server with: java 6788
and the client with: 127.0.0.1 6788
I tried other ports.
I do this in eclipse so I set the arguments in Runconfiguration before running the classes. I start the server first. I tried in terminal outside of eclipse. Nothing makes it work.
Basically, the client should connect to server and output with System.out.println() what the server in turn outputs to the client. But nothing happens.
what is wrong?
Client:
import java.io.*;
import java.net.*;
public class EchoClient {
public static void main(String[] args) throws IOException {
if (args.length != 2) {
System.err.println(
"Usage: java EchoClient <host name> <port number>");
System.exit(1);
}
String hostName = args[0];
int portNumber = Integer.parseInt(args[1]);
try (
Socket echoSocket = new Socket(hostName, portNumber);
BufferedReader in =
new BufferedReader(
new InputStreamReader(echoSocket.getInputStream()));
) {
String userInput;
while (true) {
System.out.println("recieved: " + in.readLine());
}
} catch (UnknownHostException e) {
System.err.println("Don't know about host " + hostName);
System.exit(1);
} catch (IOException e) {
System.err.println("Couldn't get I/O for the connection to " +
hostName);
System.exit(1);
}
}
}
Server:
import java.net.*;
import java.io.*;
public class EchoServer {
public static void main(String[] args) throws IOException {
if (args.length != 1) {
System.err.println("Usage: java EchoServer <port number>");
System.exit(1);
}
int portNumber = Integer.parseInt(args[0]);
System.out.println(args[0]);
InetAddress add = InetAddress.getLocalHost();
System.out.println(add.getHostAddress());
try (
ServerSocket serverSocket =
new ServerSocket(Integer.parseInt(args[0]));
Socket clientSocket = serverSocket.accept();
PrintWriter out =
new PrintWriter(clientSocket.getOutputStream());
) {
while (true) {
try {
Thread.sleep(2000);
} catch (InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
out.println("HELLO!");
}
} catch (IOException e) {
System.out.println("Exception caught when trying to listen on port "
+ portNumber + " or listening for a connection");
System.out.println(e.getMessage());
}
}
}
You have to send the answer to the client.
Add a out.flush();
while (true) {
try {
Thread.sleep(2000);
} catch (InterruptedException e) {
e.printStackTrace();
}
out.println("HELLO!");
out.flush();
}
As in the comment I eventually found a solution. BufferedReader.readLine() "blocked". When reading from a file it returns a line after reading up to a newline character, if I understand it correctly.
But since it was "A steady flow" from server with no newlines, it just kept "reading" and never returned a String.
I then tried using BufferedReader.read() method, that reads character by character, and returns after each char (thus never blocking). It then prints each character as it arrives, also it listens for a newline being sent from server, and once a read character equals a newline, it then prints a newline instead. Sort of emulating the "read line" behaviour I was expecting from original question.
Reading part of client:
while(true) {
character = (char) reader.read();
if(Character.isISOControl(character)) {
System.out.println();
}
else {
System.out.printf("%c", character);
}
}
Sending Part of Server:
private String message = "HELLO\n";
...
while(true) {
try {
Thread.sleep(2000);
writer.write(message);
writer.flush();
} catch (InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
Related
I have two classes - Provider and Requester:
Provider
import java.io.*;
import java.net.*;
public class Provider {
ServerSocket providerSocket;
Socket connection = null;
ObjectOutputStream out;
ObjectInputStream in;
String message;
Provider() {
}
void run() {
try {
// 1. creating a server socket
providerSocket = new ServerSocket(2004, 10);
// 2. Wait for connection
System.out.println("Waiting for connection");
connection = providerSocket.accept();
System.out.println(
"Connection received from " + connection.getInetAddress().getHostName());
// 3. get Input and Output streams
out = new ObjectOutputStream(connection.getOutputStream());
out.flush();
in = new ObjectInputStream(connection.getInputStream());
sendMessage("Connection successful");
// 4. The two parts communicate via the input and output streams
do {
try {
sendMessage(
"Please enter the phrase you wish to echo or the word FINISHED to exit");
message = (String) in.readObject();
sendMessage(message);
} catch (ClassNotFoundException classnot) {
System.err.println("Data received in unknown format");
}
} while (!message.equals("FINISHED"));
} catch (IOException ioException) {
ioException.printStackTrace();
} finally {
// 4: Closing connection
try {
in.close();
out.close();
providerSocket.close();
} catch (IOException ioException) {
ioException.printStackTrace();
}
}
}
void sendMessage(String msg) {
try {
out.writeObject(msg);
out.flush();
System.out.println("server>" + msg);
} catch (IOException ioException) {
ioException.printStackTrace();
}
}
public static void main(String args[]) {
Provider server = new Provider();
while (true) {
server.run();
}
}
}
Requester
import java.io.*;
import java.net.*;
import java.util.Scanner;
public class Requester {
Socket requestSocket;
ObjectOutputStream out;
ObjectInputStream in;
String message;
Scanner input;
Requester() {
input = new Scanner(System.in);
}
void run() {
try {
// 1. creating a socket to connect to the server
requestSocket = new Socket("127.0.0.1", 2004);
System.out.println("Connected to localhost in port 2004");
// 2. get Input and Output streams
out = new ObjectOutputStream(requestSocket.getOutputStream());
out.flush();
in = new ObjectInputStream(requestSocket.getInputStream());
// 3: Communicating with the server
try {
message = (String) in.readObject();
System.out.println("server>" + message);
} catch (ClassNotFoundException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
do {
try {
message = (String) in.readObject();
System.out.println(message);
message = input.nextLine();
sendMessage(message);
message = (String) in.readObject();
} catch (ClassNotFoundException classNot) {
System.err.println("data received in unknown format");
}
} while (!message.equals("FINISHED"));
} catch (UnknownHostException unknownHost) {
System.err.println("You are trying to connect to an unknown host!");
} catch (IOException ioException) {
ioException.printStackTrace();
} finally {
// 4: Closing connection
try {
in.close();
out.close();
requestSocket.close();
} catch (IOException ioException) {
ioException.printStackTrace();
}
}
}
void sendMessage(String msg) {
try {
out.writeObject(msg);
out.flush();
System.out.println("client>" + msg);
} catch (IOException ioException) {
ioException.printStackTrace();
}
}
public static void main(String args[]) {
Requester client = new Requester();
client.run();
}
}
The programs are basically meant to communicate with each other. The idea is that they each 'connect' with each other via sockets and the user should be able to enter something in the console window of Provider and have it echoed back onto the console of Requester. However, I am getting the following errors:
Provider
java.net.SocketException: Permission denied: listen failed
Requester
java.net.ConnectException: Connection refused: connect
(I can provide the rest of the errors if it would help in fixing the issue).
I have tried having the classes in the same project folder, in separate folders, and in different workspaces. I have also tried using Eclipse EE (Neon) and the SE (Oxygen). Recently, I have been having problems with ports and sockets (most notably with Tomcat and encountering the 'Cannot find free socket for debugger' in Eclipse). Would that have something to do with me being unable to run these programs?
Check your firewall settings. I was having similar problems when trying to use sockets. Make sure any relevant resources aren't blocked.
You might also want to run the command:
netstat -ano | findstr :2004
to check if that port is mistakenly in use already.
I will post my code below, a little background.
I am trying to connect to a gameserver on port 9339. my local port changes each time. The aim is to pass the packets through the proxy and display the info in the command line.
The client connects to the remote host using bluestacks which is running the game.
Code:
import java.io.*;
import java.net.*;
public class proxy {
public static void main(String[] args) throws IOException {
try {
String host = "gamea.clashofclans.com";
int remoteport = 9339;
ServerSocket ss = new ServerSocket(0);
int localport = ss.getLocalPort();
ss.setReuseAddress(true);
// Print a start-up message
System.out.println("Starting proxy for " + host + ":" + remoteport
+ " on port " + localport);
// And start running the server
runServer(host, remoteport, localport,ss); // never returns
System.out.println("Started proxy!");
} catch (Exception e) {
System.err.println(e);
}
}
/**
* runs a single-threaded proxy server on
* the specified local port. It never returns.
*/
public static void runServer(String host, int remoteport, int localport, ServerSocket ss)
throws IOException {
final byte[] request = new byte[2048];
byte[] reply = new byte[4096];
while (true) {
Socket client = null, server = null;
try {
// Wait for a connection on the local port
client = ss.accept();
System.out.println("Client Accepted!");
final InputStream streamFromClient = client.getInputStream();
final OutputStream streamToClient = client.getOutputStream();
// Make a connection to the real server.
// If we cannot connect to the server, send an error to the
// client, disconnect, and continue waiting for connections.
try {
server = new Socket(host, remoteport);
System.out.println("Client connected to server.");
} catch (IOException e) {
PrintWriter out = new PrintWriter(streamToClient);
out.print("Proxy server cannot connect to " + host + ":"
+ remoteport + ":\n" + e + "\n");
out.flush();
client.close();
System.out.println("Client disconnected");
continue;
}
// Get server streams.
final InputStream streamFromServer = server.getInputStream();
final OutputStream streamToServer = server.getOutputStream();
// a thread to read the client's requests and pass them
// to the server. A separate thread for asynchronous.
Thread t = new Thread() {
public void run() {
int bytesRead;
try {
while ((bytesRead = streamFromClient.read(request)) != -1) {
streamToServer.write(request, 0, bytesRead);
streamToServer.flush();
}
} catch (IOException e) {
}
// the client closed the connection to us, so close our
// connection to the server.
try {
streamToServer.close();
} catch (IOException e) {
}
}
};
// Start the client-to-server request thread running
t.start();
// Read the server's responses
// and pass them back to the client.
int bytesRead;
try {
while ((bytesRead = streamFromServer.read(reply)) != -1) {
streamToClient.write(reply, 0, bytesRead);
streamToClient.flush();
}
} catch (IOException e) {
}
// The server closed its connection to us, so we close our
// connection to our client.
streamToClient.close();
} catch (IOException e) {
System.err.println(e);
} finally {
try {
if (server != null)
server.close();
if (client != null)
client.close();
} catch (IOException e) {
}
}
}
}
}
Basically the last thing that is printed out is "Starting proxy for gamea.clashofclans.com:9339 on port (whatever it chose).
Hopefully someone can help me.
I have this problem too, I don`t have enough time to correct this but i think using thread is that is why all mistake.
check your proxy for working on browser setting( May be proxy had problem)
If not,
I suggest to don`t use thread. maybe mutual exclusion occurs.
Your code is correct.It is working fine so you don't need any fix. What is happening is , your serverSocket in your proxy class is waiting for client to connect. that's why it is not going forward. What you need to do is, create a client and connect to it.
follow the step :
run your proxy.
then run your client
for the client, you can use this code,
public static void main(String[] args) throws IOException {
try {
int remoteport = 9339;
String host="127.0.0.1";
makeConnection(host, remoteport);
System.out.println("connection successful!");
} catch (Exception e) {
System.err.println(e);
}
}
public static void makeConnection(String host, int remoteport) throws IOException {
while (true) {
Socket client = null;
try {
client = new Socket(host, remoteport);
System.out.println("Client connected to server.");
break;
} catch (IOException e) {
System.err.println(e);
} finally {
if (client != null)
client.close();
if (client != null)
client.close();
}
}
}
public class Main {
public static void main(String[] args) {
Server server = new Server(9008);
}
}
public class Server {
private ServerSocket server;
private Socket client;
public Server(int port) {
try {
// Create out server with our desired port
server = new ServerSocket(port);
// Server started, let the user know
System.out.println("Server started at port " + port + "...");
} catch (IOException e) {
// Unable to start server, print error
System.out.println("Unable to start server on port " + port + "...");
}
// Start our main server method
runServer();
}
public void runServer() {
while (true) {
try {
// Wait for new clients and accept them
client = server.accept();
// Let the user know - print
System.out.println("New user connected - " + client.getLocalAddress().getHostAddress());
// Start thread for our client
Thread clientThread = new Thread(new ClientConnection(client));
clientThread.start();
} catch (IOException e) {
e.printStackTrace();
}
}
}
}
So at this points everything is going fine, now inside my clientThread the problem starts
public class ClientConnection implements Runnable {
private Socket socket;
public ClientConnection(Socket client) {
// Set client socket
this.socket = client;
}
public void run() {
try {
// Read from our client input
BufferedReader readClient = new BufferedReader(new InputStreamReader(socket.getInputStream()));
String line;
while ((line = readClient.readLine()) != null) {
System.out.println("Client says - " + readClient.readLine());
}
} catch(IOException e) {
}
}
}
Is there a better way to handle this?
My actual client
public class Main {
public static void main(String args[]) {
try {
Socket socket = new Socket("localhost", 9008);
BufferedWriter writer = new BufferedWriter(new OutputStreamWriter(socket.getOutputStream()));
writer.write("Hello\n");
writer.flush();
socket.close();
} catch (UnknownHostException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
}
}
I will get "Client says - null" displayed
UPDATE: The way to read in an InputStream/Reader is somethink like
while ((myString = readClient.readLine()) != null) {
System.out.println(myString);
}
this way the loop will exit when the connection is closed.
Also, move the try/catch outside the loop, or do some error control. If you get an exception, you do not want to just try get again in the loop.
UPDATE2: In case my comment was not clear enough, over your updated code do
String line;
while ((line = readClient.readLine()) != null) {
System.out.println("Client says - " + line);
}
Just one read per iteration, at the while, so the loop can exit if line is null (that means the connection has been closed).
So I wrote a simple Socket program that send message from Client to Server program and wanted to know what is the proper procedure to go about testing this? Both my Client and Server machines are running on Ubuntu 12.04 and I'm remote connecting to both of them.
For my Client code when I instantiate the client socket (testSocket) do I use its IP Address and Port number or Servers IP Address and Port number?
Here is the Code for Client:
public static void main(String[] args) throws UnknownHostException, IOException
{
Socket testSocket = null;
DataOutputStream os = null;
DataInputStream is = null;
try
{
testSocket = new Socket("192.168.0.104", 5932);
os = new DataOutputStream(testSocket.getOutputStream());
is = new DataInputStream(testSocket.getInputStream());
}
catch (UnknownHostException e)
{
System.err.println("Couldn't find Host");
}
catch (IOException e)
{
System.err.println("Couldn't get I/O connection");
}
if (testSocket != null && os != null && is != null)
{
try
{
os.writeBytes("Hello Server!\n");
os.close();
is.close();
testSocket.close();
}
catch (UnknownHostException e)
{
System.err.println("Host not found");
}
catch (IOException e)
{
System.err.println("I/O Error");
}
}
}
Here is the code for Server:
public static void main(String[] args)
{
String line = new String() ;
try
{
ServerSocket echoServer = new ServerSocket(5932);
Socket clientSocket = echoServer.accept();
DataInputStream is = new DataInputStream(clientSocket.getInputStream());
PrintStream os = new PrintStream(clientSocket.getOutputStream());
while (true)
{
line = is.readLine();
os.println(line);
}
}
catch (IOException e)
{
System.out.println(e.getMessage());
}
}
I'm new to Sockets and not sure what I'm supposed be seeing. I compiled both programs in terminal fine but not sure which one should I be running first or do they need to be started simultaneously?
Thanks
Your server is running in a infinite loop. Avoid that.
You have to restart your computer.
while (true)
{
line = is.readLine();
os.println(line);
}
try
while (!line.equals("Hello Server!"))
{
line = is.readLine();
os.println(line);
}
Run the server first. echoServer.accept(); waits for a connection. When it gets the first connection,
http://docs.oracle.com/javase/tutorial/networking/sockets/ this is a short java tutorial on how to work with sockets and also you can learn how to make a server that would accept multiple connections at a time. This tutorial explains you always need to start the server first, which is only logical. You should use threads to manage connections and then close them so that you use resources efficiently
Im developing a client-server app. The client side is Java based, the server side is C++ in Windows.
Im trying to communicate them with Sockets, but im having some trouble.
I have succesfully communicated the client with a Java Server, to test if it was my client that was wrong, but its not, it seems like im not doing it right in the C++ version.
The java server goes like this:
import java.io.DataInputStream;
import java.io.DataOutputStream;
import java.io.IOException;
import java.net.ServerSocket;
import java.net.Socket;
public class Server {
public static void main(String[] args){
boolean again = true;
String mens;
ServerSocket serverSocket = null;
Socket socket = null;
DataInputStream dataInputStream = null;
DataOutputStream dataOutputStream = null;
try {
serverSocket = new ServerSocket(12321);
System.out.println("Listening :12321");
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
while(again){
try {
System.out.println("Waiting connection...");
socket = serverSocket.accept();
System.out.println("Connected");
dataInputStream = new DataInputStream(socket.getInputStream());
dataOutputStream = new DataOutputStream(socket.getOutputStream());
while (again){
mens = dataInputStream.readUTF();
System.out.println("MSG: " + mens);
if (mens.compareTo("Finish")==0){
again = false;
}
}
} catch (IOException e) {
System.out.println("End of connection");
//e.printStackTrace();
}
finally{
if( socket!= null){
try {
socket.close();
} catch (IOException e) {
// TODO Auto-generated catch block
//e.printStackTrace();
}
}
if( dataInputStream!= null){
try {
dataInputStream.close();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
if( dataOutputStream!= null){
try {
dataOutputStream.close();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
}
System.out.println("End of program");
}
}
The client just makes a connection and sends some messages introduced by the user.
Could you please give me a similar working server but in C++ (in Windows)?
I can't make it work by myself.
Thanx.
Your problem is that you are sending a java string which could take 1 or 2 bytes per character (see bytes of a string in java?)
You will need to send and receive in ascii bytes to make things easier, imagine data is your data string on the client side:
byte[] dataBytes = data.getBytes(Charset.forName("ASCII"));
for (int lc=0;lc < dataBytes.length ; lc++)
{
os.writeByte(dataBytes[lc]);
}
byte responseByte = 0;
char response = 0;
responseByte = is.readByte();
response = (char)responseByte;
where is and os are the client side DataInputStream and DataOutputStream respectively.
You can also sniff your tcp traffic to see what's going on :)