I am learning currently about client server communication using Java through sockets.
First of all I retrieve my own machine's IP Address using following code.
InetAddress ownIP=InetAddress.getLocalHost();
//the result being 192.168.56.1
Now I write the simple client server application using the above mentioned address as follow
public class SimpleClientServer {
public static void main(String[] args)
{
//sending "Hello World" to the server
Socket clientSocket = null;
PrintWriter out = null;
BufferedReader in = null;
try
{
clientSocket = new Socket("192.168.56.1", 16000);
out = new PrintWriter(clientSocket.getOutputStream(), true);
in = new BufferedReader(new InputStreamReader(
clientSocket.getInputStream()));
out.println("Hello World");
out.close();
in.close();
clientSocket.close();
}
catch(IOException e)
{
System.err.println("Error occured " + e);
}
}
}
The result hower reads a follow.
Error occured java.net.ConnectException: Connection refused: connect
What is the reason for this. Is it just the wrong host address?
From the code you have given you seem to suggest that there is currently nothing listening on port 16000 for the socket to connect to.
If this is the case you need to implement something like
ServerSocket serverSocket = null;
try {
serverSocket = new ServerSocket(16000);
}
catch (IOException e) {
System.err.println("Could not listen on port: 16000.");
System.exit(1);
}
More information can be found in the Java online documentation and a full example is included.
With sockets, no matter what language you're using, you either initiate a connection with socket_connect or you listen and accept with socket_listen and socket_accept. Your socket_connect call is trying to connect to an ip address that doesn't seem to be listening to anything.
Related
I want some brief idea/links for reference to start how to connect esp8266 router/access point with an android app.In esp8266 static ip is 192.168.4.1 wants to control led blink or other feautre with an android app .
how to make establish connection between esp8266 and android app .
On Android side it's just network communication without any features. Take a look at Official Documentation and tutorials like this. Everything depends on esp8266 firmware:
if it implements HTTP web server You can use HttpUrlConnection and GET or POST requests on Android side and corresponding script on esp8266 side;
if it implements ServerSocket You can use Socket connection an implement Socket Client on Android side.
Update:
Socket communication with esp8266 You should do it in separate (not UI) thread. Full example is something like that:
class SocketClientThread implements Runnable {
DataInputStream dis;
DataOutputStream dos;
String strResponseData;
#Override
public void run() {
try {
InetAddress serverAddr = InetAddress.getByName("<address>");
clientSocket = new Socket(serverAddr, <port_number - 80 in your example>);
dos = new DataOutputStream(clientSocket.getOutputStream());
dis = new DataInputStream(clientSocket.getInputStream());
// now you can write data to stream
dos.writeUTF("Hello");
// you can also read data from stream
strResponseData = dis.readUTF();
} catch (UnknownHostException ignore) {
} catch (IOException ignore) {
}
finally{
if (clientSocket != null){
try {
clientSocket.close();
}
catch (IOException ignore) {
}
}
}
}
}
And than You can use SocketClientThread this way:
Thread socketClientThread;
socketClientThread = new Thread(new SocketClientThread());
socketClientThread.start();
I tried to create a simple chat via sockets and it works for LAN right now and for "localhost" too, of course, but not among different computers through the internet and thats the real point of a chat, isn't it!
socket = new Socket("--ip address--", 7345);
This line works for --ip address-- = localhost and --ip address-- = ""my local ip-address"", but with the ip address of my router, it throws a java.net.ConnectException
" java.net.ConnectException: Connection refused: connect "
I want to use my pc as server and not a real server, maybe there is the problem, but I think that there must be a solution. If that is an absurd simple question, don't doom me, because I'm a real newbie in network programming.
When you are creating a server, you have to use server socket with the ip address of where it's running...
The server socket needs to be running on your machine of your machine's ip address.
With your router, you need to forward the connections to the port you are running on your that is hosting the server.
Then you should be able to connect from outside your local network.
Without the code for what your are doing it's hard to tell if that's the only problem here is a simple chat server that might give you guidance.
import java.net.*;
import java.io.*;
public class ChatServer
{ private Socket socket = null;
private ServerSocket server = null;
private DataInputStream streamIn = null;
public ChatServer(int port)
{ try
{
System.out.println("Binding to port " + port + ", please wait ...");
server = new ServerSocket(port);
System.out.println("Server started: " + server);
System.out.println("Waiting for a client ...");
socket = server.accept();
System.out.println("Client accepted: " + socket);
open();
boolean done = false;
while (!done)
{ try
{ String line = streamIn.readUTF();
System.out.println(line);
done = line.equals(".bye");
}
catch(IOException ioe)
{
done = true;
}
}
close();
}
catch(IOException ioe)
{ System.out.println(ioe);
}
}
public void open() throws IOException
{ streamIn = new DataInputStream(new BufferedInputStream(socket.getInputStream()));
}
public void close() throws IOException
{ if (socket != null) socket.close();
if (streamIn != null) streamIn.close();
}
public static void main(String args[])
{ ChatServer server = null;
if (args.length != 1)
System.out.println("Usage: java ChatServer port");
else
server = new ChatServer(Integer.parseInt(args[0]));
}
}
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
I'm trying to test a scenario where one server accepts connections(one each time) from one client, using always the same ports (on the server and on the client side).
The purpose is to have 1 client application sending little pieces of data at a rate bigger than 100/min. The well obvious solution would be to have an always connected link between the client and the server, but this is production stuff, and that would require bigger changes in the code that is already implemented. With the solution we have implemented today, we always have +-1K of connections in TIME_WAIT, and I want to get rid of them.
I have implemented a simple tester, and the code is:
public class Server {
public static void main(String[] args) {
ServerSocket ssock = null;
try {
ssock = new ServerSocket();
ssock.bind(new InetSocketAddress(Common.SERVER_PORT));
} catch (IOException e) {
e.printStackTrace();
System.exit(-1);
}
while(true){
try{
Socket cSock = ssock.accept();
BufferedReader reader = new BufferedReader(new InputStreamReader(cSock.getInputStream()));
reader.readLine();
PrintWriter writer = new PrintWriter(cSock.getOutputStream());
writer.println(Common.SERVER_SEND);
writer.flush();
reader.close();
writer.close();
cSock.close();
}catch (Exception e) {
System.out.println(e.getClass().getName() + ": " + e.getMessage());
}
}
}
}
public class Client {
public static void main(String[] args) throws Exception {
InetSocketAddress cliAddr = new InetSocketAddress(
InetAddress.getByName(args[0]),
Common.CLIENT_PORT);
InetSocketAddress srvAddr = new InetSocketAddress(
InetAddress.getByName(args[1]),
Common.SERVER_PORT);
for(int j=1;j<=50;j++){
Socket sock = null;
try{
sock = new Socket();
sock.setReuseAddress(true);
sock.bind(cliAddr);
sock.connect(srvAddr);
PrintWriter writer =
new PrintWriter(
sock.getOutputStream());
writer.println(Common.CLIENT_SEND);
writer.flush();
BufferedReader reader =
new BufferedReader(
new InputStreamReader(
sock.getInputStream()));
reader.readLine();
}catch (Exception e) {
System.out.println(e.getClass().getName() + ": " + e.getMessage());
System.exit(-1);
}finally{
if(sock!=null) sock.close();
System.out.println("Done " + j);
}
}
}
}
public class Common {
public static final int SERVER_PORT = 9009;
public static final int CLIENT_PORT = 9010;
public static final String CLIENT_SEND = "Message";
public static final String SERVER_SEND = "OK";
}
When executing the client and server, on windows hosts, in one client execution I always get
java.net.ConnectException: Connection timed out
When executing the client and the server in linux hosts, on some client executions I get a
java.net.NoRouteToHostException: Cannot assign requested address
I've been killing my head over this behavior. Can someone please tell me if it is possible to do what I want, and what I am doing wrong?
If you want to get rid of the TIME_WAIT state, don't be the peer that receives the close. Be the peer that initiates the close. In this case, close the connection immediately after reading the response, and have the server cycle around looking for another request so that it reads the EOF rather than just closing the connection immediately after sending the response. However this will only make the problem worse, as all the TIME_WAIT states will accumulate at the server rather than at the client. On the other hand, the server is now structured to accept multiple requests per connection, so then all you have to do is adapt the clients to use a connection pool and all your problems are solved.
I am fairly new to java and I am currently experimenting with sockets and buffers.
What I wanted to try was just to instantiate a connection from one local java app and another. I am using ServerSocket and Socket.
The server app has a thread that listens for connections:
public void run() {
try{
ServerSocket serverSock = new ServerSocket(62666);
while(doRun){
Socket sock = serverSock.accept();
BufferedReader reader = new BufferedReader(new InputStreamReader(sock.getInputStream()));
InfoReader.gui.writeToTextArea(reader.readLine() + "\n");
reader.close();
}
}catch(IOException e){
e.printStackTrace();
}
}
The "client" simply sends a string to the server (well it should, but I can't make it work):
try{
Socket sock = new Socket("127.0.0.1",62666);
PrintWriter writer = new PrintWriter(sock.getOutputStream());
writer.print("Connection works!");
}catch(IOException e){
e.printStackTrace();
}
I am sure that the port is open and forwarded to the local machine already. I've checked on http://canyouseeme.org/.
I've also tried using my external IP address as the IP of the socket in the client. It did not work either.
Any help appreciated :).
Mike.
Ok, then as an answer so you can close the question ;-)
Add a flush() and a close() to the Writer.
Hope that helps. :-)