I am trying to implement this example here: Reading from and Writing to a Socket
I copied and pasted the code into NetBeans. I changed the port name "taranis" to "localhost" and tried to run the example, but I got the error:
run: Couldn't get I/O for the connection to: localhost. Java Result: 1
BUILD SUCCESSFUL (total time: 1 second)
I also tried to substitute localhost for my actual hostname of my laptop, but it gives the similar error. Can you help pinpoint what I am doing wrong?
Edit: In regards to Mark's recommendation, when I substitute
System.err.println("Couldn't get I/O for " + "the connection to: localhost.");
with
e.printStackTrace();
I get:
run:
java.net.ConnectException: Connection refused: connect
at java.net.PlainSocketImpl.socketConnect(Native Method)
at java.net.PlainSocketImpl.doConnect(PlainSocketImpl.java:351)
at java.net.PlainSocketImpl.connectToAddress(PlainSocketImpl.java:213)
at java.net.PlainSocketImpl.connect(PlainSocketImpl.java:200)
at java.net.SocksSocketImpl.connect(SocksSocketImpl.java:366)
at java.net.Socket.connect(Socket.java:529)
at java.net.Socket.connect(Socket.java:478)
at java.net.Socket.<init>(Socket.java:375)
at java.net.Socket.<init>(Socket.java:189)
at EchoClient.main(EchoClient.java:12)
Java Result: 1
BUILD SUCCESSFUL (total time: 3 seconds)
The echo service is not listening. Why not write your own? Run the application below and change your client to connect to the same port (8000).
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 EchoServer {
private static final int PORT = 8000;
public static void main(String[] args) throws Exception {
ServerSocket serverSocket = null;
try {
serverSocket = new ServerSocket(PORT);
}
catch (IOException e) {
System.err.println("Could not listen on port: " + PORT);
System.exit(1);
}
Socket clientSocket = null;
try {
clientSocket = serverSocket.accept();
}
catch (IOException e) {
System.err.println("Accept failed.");
System.exit(1);
}
PrintWriter out = new PrintWriter(clientSocket.getOutputStream(), true);
BufferedReader in = new BufferedReader(new InputStreamReader(clientSocket.getInputStream()));
System.out.println("Echo server started");
String inputLine;
while ((inputLine = in.readLine()) != null) {
System.out.println("echoing: " + inputLine);
out.println(inputLine);
}
out.close();
in.close();
clientSocket.close();
serverSocket.close();
}
}
Btw, the next example (knock-knock server) does work and gives a nice example of using a 'protocol' class.
I don't think the echo service is running by default, when I tried a quick test it on my Win XP client, it did not work:
H:\>telnet localhost 7
Connecting To localhost...Could not open connection to the host, on port 7:
Connect failed
H:\>
So to make your code work, you could try pointing it to a server that has the echo service running.
For future reference, the echo service is commonly disabled by default. I'm using windows 7, to enable it I followed the instructions found here:
http://www.windowsnetworking.com/articles_tutorials/windows-7-simple-tcpip-services-what-how.html
Example worked fine for me afterwards.
For XP:
http://www.microsoft.com/resources/documentation/windows/xp/all/proddocs/en-us/sag_tcpip_pro_simptcpinstall.mspx?mfr=true
Related
import java.io.BufferedReader;
import java.io.BufferedWriter;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.OutputStreamWriter;
import java.io.PrintWriter;
import java.net.Socket;
public class FTPClient {
protected Socket sk;
protected BufferedReader in;
protected BufferedWriter out;
public static void main (String [] args){
FTPClient fc1 = new FTPClient("sitename.org",21);
fc1.Login("user", "password!");
}
FTPClient(String server, int port){
try{
this.sk = new Socket(server,port);
this.in = new BufferedReader(new InputStreamReader(sk.getInputStream()));
this.out = new BufferedWriter(new OutputStreamWriter(sk.getOutputStream()));
String response = in.readLine();
System.out.println(response);
}
catch(Exception e){
System.out.println(e);
}
}
public boolean Login(String user, String pass){
boolean success = false;
try{
sendOut("USER " + user);
sendOut("PASS " + pass);
success = true;
System.out.println("Waiting for response");
String response = in.readLine();
System.out.println(response);
}
catch(Exception e){
System.out.println("Login Failure");
success = false;
}
return(success);
}
public void sendOut(String command) throws Exception{
if (sk == null){
throw new Exception("Client is not connected!");
}
try{
out.write(command + "\r\n");
out.flush();
}
catch(Exception e){
System.out.println(e);
}
}
}
Hello, I wrote this code as a client to try to connect and login to a server with an FTP connection. However, I keep getting this error message,
java.net.ConnectException: Connection refused: connect
Can someone please help me?
You try to connect to a SSH server, hence you get the unexpected reply. The defualt FTP port is 21.
Ok... My School's server doesn't have FTP set up and opened on port 21. So, I started FTP on my server on port 21 and it properly connect now. Thanks for helping me trouble shoot guys.
Lessons learned: FTP is normally on port 21. However, if there are connection problems, one should check if the server is even listening on port 21 by logging on and using the "sudo netstat netstat -lntu" command. If FTP is not even on, one can install it by running "sudo apt-get install vsftpd".
Thanks everyone for helping me troubleshoot to the answer.
This question already has answers here:
Exception in thread "main" java.net.BindException: Address already in use - Error in Netbeans only
(6 answers)
Closed 7 years ago.
I am trying to run the following code by first running the chatserver file and then the chatclient file.
import java.net.*;
import java.io.*;
public class chatserver
{
public static void main(String args[]) throws Exception
{
ServerSocket ss=new ServerSocket(2000);
Socket sk=ss.accept();
BufferedReader cin=newBufferedReader(newInputStreamReader(sk.getInputStream()));
PrintStream cout=new PrintStream(sk.getOutputStream());
BufferedReader stdin=new BufferedReader(new InputStreamReader(System.in));
String s;
while ( true )
{
s=cin.readLine();
if (s.equalsIgnoreCase("END"))
{
cout.println("BYE");
break;
}
System. out.print("Client : "+s+"\n");
System.out.print("Server : ");
s=stdin.readLine();
cout.println(s);
}
ss.close();
sk.close();
cin.close();
cout.close();
stdin.close();
}
}
public class chatclient
{
public static void main(String args[]) throws Exception
{
Socket sk=new Socket("192.168.0.19",2000);
BufferedReader sin=new BufferedReader(new InputStreamReader(sk.getInputStream()));
PrintStream sout=new PrintStream(sk.getOutputStream());
BufferedReader stdin=new BufferedReader(new InputStreamReader(System.in));
String s;
while ( true )
{
System.out.print("Client : ");
s=stdin.readLine();
sout.println(s);
s=sin.readLine();
System.out.print("Server : "+s+"\n");
if ( s.equalsIgnoreCase("BYE") )
break;
}
sk.close();
sin.close();
sout.close();
stdin.close();
}
}
But it is not working. What are the correct procedure/steps to run a this kind of application?
Running the server file gives the following error.
Exception in thread "main" java.net.BindException: Address already in use: JVM_Bind
at java.net.DualStackPlainSocketImpl.bind0(Native Method)
at java.net.DualStackPlainSocketImpl.socketBind(DualStackPlainSocketImpl.java:106)
at java.net.AbstractPlainSocketImpl.bind(AbstractPlainSocketImpl.java:382)
at java.net.PlainSocketImpl.bind(PlainSocketImpl.java:190)
at java.net.ServerSocket.bind(ServerSocket.java:375)
at java.net.ServerSocket.<init>(ServerSocket.java:237)
at java.net.ServerSocket.<init>(ServerSocket.java:128)
at javaapplication1.chatserver.main(chatserver.java:19)
Java Result: 1
Address already in use means some program is already listening on port 2000 (most likely the same program that you didn't shutdown properly).
Try out a different port.
You may use the netstat command on your command line to see which ports are currently in use.
Here is your working example:
// Server
package test;
import java.io.BufferedReader;
import java.io.InputStreamReader;
import java.io.PrintStream;
import java.net.ServerSocket;
import java.net.Socket;
public class Server {
public Server() {
// TODO Auto-generated constructor stub
}
public static void main(String args[]) throws Exception
{
System.out.println("Server started");
ServerSocket ss=new ServerSocket(8888);
System.out.println("Server waiting for connection");
Socket sk=ss.accept();
System.out.println("Server Connected");
BufferedReader cin=new BufferedReader(new InputStreamReader(sk.getInputStream()));
PrintStream cout=new PrintStream(sk.getOutputStream());
BufferedReader stdin=new BufferedReader(new InputStreamReader(System.in));
String s;
while ( true )
{
s=cin.readLine();
if (s.equalsIgnoreCase("END"))
{
cout.println("BYE");
break;
}
System. out.print("Client : "+s+"\n");
System.out.print("Server : ");
s=stdin.readLine();
cout.println(s);
}
ss.close();
sk.close();
cin.close();
cout.close();
stdin.close();
}
}
// Client
package test;
import java.io.BufferedReader;
import java.io.InputStreamReader;
import java.io.PrintStream;
import java.net.Socket;
public class Client {
public Client() {
// TODO Auto-generated constructor stub
}
public static void main(String args[]) throws Exception
{
System.out.println("Client started");
Socket sk=new Socket("localhost",8888);
System.out.println("Client Connected");
BufferedReader sin=new BufferedReader(new InputStreamReader(sk.getInputStream()));
PrintStream sout=new PrintStream(sk.getOutputStream());
BufferedReader stdin=new BufferedReader(new InputStreamReader(System.in));
String s;
while ( true )
{
System.out.print("Client : ");
s=stdin.readLine();
sout.println(s);
s=sin.readLine();
System.out.print("Server : "+s+"\n");
if ( s.equalsIgnoreCase("BYE") )
break;
}
sk.close();
sin.close();
sout.close();
stdin.close();
}
}
Address already in use: JVM_Bind
Java application is trying to connect on port 2000 but that port is already used by some other process and JVM Bind to that particular port 2000, is failed. Now to fix this error you need to find out which process is listening of port 2000
Windows users:
In Command Prompt, send command "netstat -ao". You can get network information for all processes.
Find out the one using port 2000, get the PID.
Find out the process with the PID you just got from windows task manager and shut it down. (By default the Task Manager doesn't show the PID. You have to add it from the menu View | Select columns)
Restart Server.
Restart the application you've just shutdown.
Unix users:
Most Unix systems have the built-in fuser command that returns the process which is engaging a port:
fuser -v -n (tcp | udp) <port#>
but if you can not kill that process than you need to change your web-server configuration or eclipse configuration to listen on different port. In case of tomcat you can change it on connector section of server.xml and in case of eclipse you can see here setting up Eclipse for Java remote debugging.
Change the port number you are using to run your application.
For more check this link- http://www.mastertheboss.com/jboss-server/jboss-configuration/solving-javanetbindexception-address-already-in-use-jvmbind
your port 2000 is already in use by another process.
try using the netstat command on your commandline to see which port are in use.
I usually use 5 digit ports like 10999 which is uncommon.
You are using the same port for both client and server: 2000, that's why starting client fails because only one process can use a socket, so if server takes it then client can't.
I don't know how to clearly describe my question in title, as for me it is a little complicated. What i am doing is try to implement a TCP peer to peer demo, in which a local port must be both for listening and initiating a socket.
I will give a detailed description.
I will give a java implementation which will listen and initiate connection on a single local port. Code will explain my idea.
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.OutputStream;
import java.io.PrintWriter;
import java.net.InetSocketAddress;
import java.net.ServerSocket;
import java.net.Socket;
/**
* Just for testing socket SO_RESUEADDR. If set SO_RESUEADDR to true, we can use
* a single local port to listen for incoming TCP connections, and to initiate
* multiple outgoing TCP connections concurrently. By this way we can implement
* TCP hole punching(establish P2P connection traversal through NAT over TCP).
*/
public class TcpPeer {
// TCP port is a different source from UDP port, it means you can listen on
// same port for both TCP and UDP at the same time.
private int localport = 7890;
private ServerSocket peerSock;
private Socket serverSocket;
public TcpPeer(final String serverHost, final int serverPort, final int localPort)
throws Exception {
this.localport = localPort;
Thread server = new Thread(new Runnable() {
#Override
public void run() {
try {
peerSock = new ServerSocket();
peerSock.setReuseAddress(true);
peerSock.bind(new InetSocketAddress("localhost", localport));
System.out.println("[Server]The server is listening on " + localport + ".");
while (true) {
try {
serverSocket = peerSock.accept();
// just means finishing handshaking, and connection
// established.
System.out.println("[Server]New connection accepted"
+ serverSocket.getInetAddress() + ":" + serverSocket.getPort());
BufferedReader br = getReader(serverSocket);
PrintWriter pw = getWriter(serverSocket);
String req = br.readLine();
System.out.println("[Server][REQ]" + req);
pw.println(req);
pw.close();
br.close();
} catch (IOException e) {
e.printStackTrace();
} finally {
try {
if (serverSocket != null)
serverSocket.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
} catch (Exception e) {
e.printStackTrace();
}
}
});
// server.setDaemon(true);
server.start();
Thread.currentThread();
// sleep several seconds before launch of client
Thread.sleep(5 * 1000);
final int retry = 5;
Thread client = new Thread(new Runnable() {
#Override
public void run() {
Socket socket = new Socket();
try {
socket.setReuseAddress(true);
System.out.println("[Client]socket.isBound():" + socket.isBound());
socket.bind(new InetSocketAddress("localhost", localport));
for (int i = 1; i < retry; i++) {
try {
socket.connect(new InetSocketAddress(serverHost, serverPort));
System.out.println("[Client]connect to " + serverHost + ":"
+ serverPort + " successfully.");
break;
} catch (Exception e) {
e.printStackTrace();
System.out.println("[Client]fail to connect " + serverHost + ":"
+ serverPort + ", try again.");
Thread.currentThread().sleep(i * 2 * 1000);
if (i == retry - 1) return;
}
}
PrintWriter pw = getWriter(socket);
String msg = "hello world!";
pw.println(msg);
/**
* Got response from the server socket.
*/
BufferedReader br = getReader(socket);
String resp = br.readLine();
System.out.println("[Client][RESP-1]" + resp);
pw.close();
br.close();
} catch (Exception e) {
e.printStackTrace();
} finally {
try {
socket.close();
} catch (Exception e) {
e.printStackTrace();
}
}
}
});
client.start();
}
private PrintWriter getWriter(Socket socket) throws IOException {
OutputStream socketOut = socket.getOutputStream();
return new PrintWriter(socketOut, true);
}
private BufferedReader getReader(Socket socket) throws IOException {
InputStream socketIn = socket.getInputStream();
return new BufferedReader(new InputStreamReader(socketIn));
}
public static void main(String[] args) throws Exception {
if (args.length != 3) {
System.out.println("[Usage] java " + TcpPeer.class.getCanonicalName()
+ " [serverHost] [serverPort] [localPort]");
System.exit(0);
}
new TcpPeer(args[0], Integer.parseInt(args[1]), Integer.parseInt(args[2]));
}
}
Now we launch 2 jvm processes:
ps#1> java TcpPeer localhost 2000 4000
ps#2> java TcpPeer localhost 4000 2000
Finally when 2 processes got stable, they will give below outputs:
ps#1>
[Server]The server is listening on 2000.
[Client]socket.isBound():false
[Client]connect to localhost:4000 successfully.
[Client][RESP-1]hello world!
ps#2>
[Server]The server is listening on 4000.
[Server]New connection accepted/127.0.0.1:2000
[Server][REQ]hello world!
[Client]socket.isBound():false
java.net.BindException: Address already in use: connect
at java.net.PlainSocketImpl.socketConnect(Native Method)
at java.net.PlainSocketImpl.doConnect(PlainSocketImpl.java:333)
at java.net.PlainSocketImpl.connectToAddress(PlainSocketImpl.java:195)
at java.net.PlainSocketImpl.connect(PlainSocketImpl.java:182)
at java.net.SocksSocketImpl.connect(SocksSocketImpl.java:366)
at java.net.Socket.connect(Socket.java:525)
at java.net.Socket.connect(Socket.java:475)
at org.clinic4j.net.TcpPeer$2.run(TcpPeer.java:92)
at java.lang.Thread.run(Thread.java:619)
[Client]fail to connect localhost:2000, try again.
java.net.SocketException: Socket operation on nonsocket: connect
at java.net.PlainSocketImpl.socketConnect(Native Method)
at java.net.PlainSocketImpl.doConnect(PlainSocketImpl.java:333)
at java.net.PlainSocketImpl.connectToAddress(PlainSocketImpl.java:195)
at java.net.PlainSocketImpl.connect(PlainSocketImpl.java:182)
at java.net.SocksSocketImpl.connect(SocksSocketImpl.java:366)
at java.net.Socket.connect(Socket.java:525)
at java.net.Socket.connect(Socket.java:475)
at org.clinic4j.net.TcpPeer$2.run(TcpPeer.java:92)
at java.lang.Thread.run(Thread.java:619)
[Client]fail to connect localhost:2000, try again.
java.net.SocketException: Socket operation on nonsocket: connect
at java.net.PlainSocketImpl.socketConnect(Native Method)
at java.net.PlainSocketImpl.doConnect(PlainSocketImpl.java:333)
at java.net.PlainSocketImpl.connectToAddress(PlainSocketImpl.java:195)
at java.net.PlainSocketImpl.connect(PlainSocketImpl.java:182)
at java.net.SocksSocketImpl.connect(SocksSocketImpl.java:366)
at java.net.Socket.connect(Socket.java:525)
at java.net.Socket.connect(Socket.java:475)
at org.clinic4j.net.TcpPeer$2.run(TcpPeer.java:92)
at java.lang.Thread.run(Thread.java:619)
[Client]fail to connect localhost:2000, try again.
java.net.SocketException: Socket operation on nonsocket: connect
at java.net.PlainSocketImpl.socketConnect(Native Method)
at java.net.PlainSocketImpl.doConnect(PlainSocketImpl.java:333)
at java.net.PlainSocketImpl.connectToAddress(PlainSocketImpl.java:195)
at java.net.PlainSocketImpl.connect(PlainSocketImpl.java:182)
at java.net.SocksSocketImpl.connect(SocksSocketImpl.java:366)
at java.net.Socket.connect(Socket.java:525)
at java.net.Socket.connect(Socket.java:475)
at org.clinic4j.net.TcpPeer$2.run(TcpPeer.java:92)
at java.lang.Thread.run(Thread.java:619)
[Client]fail to connect localhost:2000, try again.
From the output, we can figure out that interaction flow as below:
ps#1 listen on 2000.
ps#2 listen on 4000.
ps#1 connect to ps#2, from localhost:2000 -> localhost:4000.
ps#2 close the connection which established at step#3.
ps#2 try to connect to ps#1 at 2000, failed!
Why ps#2 cannot connect to ps#1 at step#4? I also monitor the net status of OS.
Below is net status right after step#3.
And also the net status right after step#4.
192.168.2.107 is localhost
Could you please give me a comment on my case? thanks!
I have printed out the original exception message when fail to reconnect, but i don't have much idea about those exception.
You shouldn't bind the client socket, and also not set the SO_REUSEADDR on client socket.
If you do not bind a client socket, the system will automatically assign a port number for you.
Also, SO_REUSEADDR doesn't mean the address (ip/port numbers) can be reused while the socket is still open. It's so that when a socket has been closed and is in the TIME_WAIT state, you can bind to that again.
Your client thread exits just after the first exchange of messages, it lacks while(true) part.
If you get through your connection retries without a successful connection you need to quit, not fall through into the I/O code. This is why you are getting the actual exception.
You also need to print out why the connections are failing. At the moment this is the most important information, and you are suppressing it. Print the exception message. This is a general principle: don't make up your own message, use the one you're given. It is almost certainly more specific.
Instead of new InetAddress("localhost") use null when binding the ServerSocket.
I'm not convinced that you can retry a connect on a socket. If it fails, try creating a new Socket.
I'm learning about sockets in java. I was able to connect a client socket to an online server, but I can connect them to my own server socket!
import java.io.IOException;
import java.net.ServerSocket;
import java.net.Socket;
class Blargh2 {
public static void main(String[] args) {
Socket client = null;
ServerSocket server = null;
System.out.println("Line one reacehd!");
try {
server = new ServerSocket(4445);
} catch (Exception e) {
System.out.println("Error:" + e.getMessage());
}
System.out.println("Line two reacehd!");
try {
client = server.accept();
} catch (IOException e) {
System.out.println("Accept failed: 4444");
System.exit(-1);
}
System.out.println("Line three reacehd!");
try {
server.close();
client.close();
} catch (IOException e) {
System.out.println("Accept failed: 4444");
System.exit(-1);
}
}
}
The program reaches lines one and two but it never reaches line 3!
Can anyone help me solve this? Firewall also allows this connection...
It never reaches line 3 because you need a remote TCP socket (although it can be local, for testing) to connect to your socket on port 4445. You accept endpoint sockets on the server, which are used for communication with the remote client. There is actually no client here, so it waits indefinitely or until a timeout on the accept() call.
Try running this code and after you see line 2 is executed, then run the windows command:
telnet localhost 4445
Then you should see your line 3 executed.
A server software my client communicates with regularly sends transaction messages on port 4000. I need to print those messages to the console line by line. (Eventually I will have to write those values to a table, but I’m saving that for later.)
I tried this code but it doesn’t output anything:
package merchanttransaction;
import java.io.IOException;
import java.io.ObjectInputStream;
import java.io.ObjectOutputStream;
import java.lang.ClassNotFoundException;
import java.net.InetAddress;
import java.net.Socket;
import java.net.UnknownHostException;
public class MerchantTransaction {
public static void main(String[] args) {
try {
InetAddress host = InetAddress.getLocalHost();
Socket socket = new Socket("192.168.1.104", 4000);
ObjectInputStream ois = new ObjectInputStream(socket.getInputStream());
String message = (String) ois.readObject();
System.out.println("Message: " + message);
ois.close();
} catch (UnknownHostException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
} catch (ClassNotFoundException e) {
e.printStackTrace();
}
}
}
By the way, I need to be able to monitor that port until the program terminates. I’m not sure if the code above will be able to do that because I don’t see any iteration to the code.
I’m using Java version 1.6.0_24, SE Runtime Environment (build 1.6.0_24-b07) running on Ubuntu.
You need to use a ServerSocket. You can find an explanation here.
What do you actually want to achieve? What your code does is it tries to connect to a server located at 192.168.1.104:4000. Is this the address of a server that sends the messages (because this looks like a client-side code)? If I run fake server locally:
$ nc -l 4000
...and change socket address to localhost:4000, it will work and try to read something from nc-created server.
What you probably want is to create a ServerSocket and listen on it:
ServerSocket serverSocket = new ServerSocket(4000);
Socket socket = serverSocket.accept();
The second line will block until some other piece of software connects to your machine on port 4000. Then you can read from the returned socket. Look at this tutorial, this is actually a very broad topic (threading, protocols...)
Try this piece of code, rather than ObjectInputStream.
BufferedReader in = new BufferedReader (new InputStreamReader (socket.getInputStream ()));
while (true)
{
String cominginText = "";
try
{
cominginText = in.readLine ();
System.out.println (cominginText);
}
catch (IOException e)
{
//error ("System: " + "Connection to server lost!");
System.exit (1);
break;
}
}