Java Socket Programming => only IE9 works? - java

I am creating a multithread server program to display the browser's request when it try to connect to localhost.
I found only IE9 on my Windows works as expected but not Firefox 19, Chrome, Opera. The are simply sitting there to wait for my program response.
What I have missed?
import java.io.*;
import java.net.*;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.logging.Level;
import java.util.logging.Logger;
public class HTTPEchoServer {
private static final String serverName = "HTTPEchoServer";
private static final int port = 80;
private static final String CRLF = "\r\n";
private static final Logger logger = Logger.getLogger(serverName);
private static void printHeader(PrintWriter out) {
out.println("HTTP/1.0 200 OK\r\n" + "Server: " + serverName + CRLF
+ "Content-Type: text/html" + CRLF + CRLF
+ "<!DOCTYPE HTML PUBLIC "
+ "\"-//W3C//DTD HTML 4.0 Transitional//EN\">\n"
+ "<HTML>\n"
+ "<HEAD>\n"
+ " <TITLE>" + "HTTP Echo Server Result</TITLE>\n"
+ "</HEAD>\n"
+ "<H1>HTML Received from HTTP Echo Server</H1>\n"
+ "<B>Here is the request sent by your browser:</B>\n"
+ "<PRE>");
}
private static void printTrailer(PrintWriter out) {
out.println("</PRE>\n" + "</BODY>\n" + "</HTML>\n");
}
static class ClientHandler extends Thread {
Socket socket = null;
public ClientHandler(Socket socket) {
this.socket = socket;
}
#Override
public void run() {
logger.log(Level.INFO, "Accepted client {0}:{1}",
new Object[]{socket.getInetAddress(), socket.getPort()});
try {
InputStream is = socket.getInputStream();
OutputStream os = socket.getOutputStream();
try (PrintWriter writer = new PrintWriter(os, true)) {
synchronized (this) {
printHeader(writer);
writer.flush();
BufferedReader reader = new BufferedReader
(new InputStreamReader(is));
String line;
while ((line = reader.readLine()) != null) {
writer.println(line);
writer.flush();
}
printTrailer(writer);
writer.flush();
writer.close();
}
}
socket.close();
} catch (IOException ex) {
logger.log(Level.SEVERE, null, ex);
}
logger.log(Level.INFO, "Disconnected client {0}:{1}",
new Object[]{socket.getInetAddress(), socket.getPort()});
}
}
public static void main(String[] args) {
try {
ServerSocket server = new ServerSocket(port);
logger.log(Level.INFO, "Server started, listening at port {0} ...", port);
ExecutorService executor = Executors.newCachedThreadPool();
while (true) {
Socket socket = server.accept();
ClientHandler handler = new ClientHandler(socket);
executor.execute(handler);
}
} catch (IOException ex) {
logger.log(Level.SEVERE, null, ex);
}
}
}
Also, I found I cannot run this program on the OS X unless I change the port to 8080. I have already disabled the firewall on my OS X 10.8.2 computer. The error I get is:
<pre>
java.net.BindException: Permission denied
at java.net.PlainSocketImpl.socketBind(Native Method)
at java.net.AbstractPlainSocketImpl.bind(AbstractPlainSocketImpl.java:376)
at java.net.ServerSocket.bind(ServerSocket.java:376)
at java.net.ServerSocket.<init>(ServerSocket.java:237)
at java.net.ServerSocket.<init>(ServerSocket.java:128)
at HTTPEcho.HTTPEchoServer.main(HTTPEchoServer.java:80)
</pre>

You cannot open server socket in applet in all browsers except MSIE. This is done because opening server socket is security violation. If you do want to do this you have to sign your applet.
I hope that I understood your correctly that your code is running in applet environment (because you mentioned browsers) although I cannot see this facet from your stack trace that starts from main().
EDIT:
I read your post again and understood that your question actually contains 2 questions: first about applets and second about running as application under Unix. For unix #Anders R. Bystrup gave you the answer: only root can listen to ports under 1024. So, you have to run your program as root or using sudo.
BTW it seems that you are on the wrong way. Could you probably explain what would you like to achieve and community probably can give you a tip for better solution.

As the exception itself says java.net.BindException: Permission denied. You need to be root user to bind ports below 1024. If you are on linux you san do sudo java HTTPEchoServer to start the server.
Other possibility may be that you already have a server running on port 80.

Port 80 is reserved HTTP port, there are other ports aswell which are reserved.
ports 1 through 1023 for administrative functions leaving port numbers greater than 1024 available for use.
How to find available port

Related

Get full URL path from browser with using ServerSocket and Socket classes

I'm trying write my individual HTTP Server and I need a help .
What is the method of ServerSocket or Socket class can to invoke on the URL and brining it into a code.
For example, if I write following link <b>http://localhost:8080/coupon/add?name=coupon name</b> in browser, I would be want to get this link into my code.
Maybe who know how can I do this?
my simple code:
import java.io.IOException;
import java.net.ServerSocket;
import java.net.Socket;
public class HTTPServer {
public static void main(String[] args) {
new HTTPServer().startServer();
}
public void startServer() {
try (ServerSocket serverSocket = new ServerSocket(8080)) {
System.out.println("Server is started");
while (true) {
Socket socket = serverSocket.accept();
}
} catch (IOException e) {
e.printStackTrace();
}
}
}
Thanks
All your code does right now is set up a TCP server.
HTTP is a Layer 7 protocol.
Once you accept the connection from the client, HTTP can be used for communication over that TCP socket.
You'd have to parse the HTTP request that the client sends, and from that, you'd know the URL.
In your case, you said:
I write following link http://localhost:8080/coupon/add?name=coupon name in browser
Your browser will send an HTTP request like the following example:
GET /coupon/add?name=coupon+name HTTP/1.0
Host: localhost:8080
In reality, there will be more HTTP headers there, as well as a trailing \r\n, but for our sake, let's keep it simple.
Note that special characters like space are URL-encoded, however space is also encoded as + in the query string - it could be either + or %20 depending on the client.
Hopefully it's reasonably clear to you from this explanation how you get the URL from this HTTP request.
The only missing part from the actual full link is the http:// part. The distinction between HTTP and HTTPS is not part of the HTTP protocol - it's above the socket layer but below the HTTP protocol layer. If you had SSL sockets, you'd know that on the server side, and determine based on whether it was an SSL socket or a "plain" socket, whether it was http or https.
Hope that helps.
I improved for testing the startServer method for getting information.
I'm trying to include the data that comes from URL from any browsers to URI or URL class of JAVA.
This impossible ? Maybe who know how can I do this ?
public void startServer() {
try (ServerSocket serverSocket = new ServerSocket(8080)) {
System.out.println("Server is started");
while (true) {
Socket socket = serverSocket.accept();
System.out.println("SERVER SOCKET TESTS:");
System.out.println("getChannel: " + serverSocket.getChannel());
System.out.println("getInetAddress: " + serverSocket.getInetAddress());
System.out.println("getLocalPort: " + serverSocket.getLocalPort());
System.out.println("getLocalSocketAddress: " + serverSocket.getLocalSocketAddress());
System.out.println();
System.out.println("CLIENT SOCKET TESTS:");
System.out.println("getChannel: " + socket.getChannel());
System.out.println("getLocalAddress: " + socket.getLocalAddress());
System.out.println("getLocalPort: " + socket.getLocalPort());
System.out.println("getLocalSocketAddress: " + socket.getLocalSocketAddress());
System.out.println("getRemoteSocketAddress: " + socket.getRemoteSocketAddress());
System.out.println("getInetAddress: " + socket.getInetAddress());
System.out.println("getInputStream: " + socket.getInputStream());
System.out.println("getOutputStream: " + socket.getOutputStream());
System.out.println();
System.out.println("URI - GET INFORMATION:");
URI uri = new URI("httpscheme://world.hello.com/thismy?parameter=value");
System.out.println(uri.getHost());
System.out.println(uri.getPath());
System.out.println(uri.getQuery());
System.out.println(uri.getScheme());
}
} catch (Exception e) {
System.out.println("error");
}
}
little test:
when I run code and after that open the browser and I write in my browser, for example: http://localhost:8080 I get information, but I don't understand following:
why the serverSocket object in getInetAddress method (serverSocket.getInetAddress) have an IP4 and it 0.0.0.0 (why not a standard local ip that defined on my computer) and the socket object of getInetAddress method (socket.getInetAddress) have an IP6 and it 0:0:0:0:0:0:0:1 . How can I get a standard host name localhost how to get the URI class (with chunks of data of link)?
The port is gated nice: 8080.
The problem for getting URL path , solved.
package pk6HttpServer;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.Reader;
import java.net.MalformedURLException;
import java.net.ServerSocket;
import java.net.Socket;
/**
* Created by Morris on 08/10/16.
*/
public class HTTPServer {
private static String headerData;
public static void main(String[] args) {
new HTTPServer().startServer();
}
public void startServer() {
try (ServerSocket serverSocket = new ServerSocket(8080)) {
boolean isClosed = false;
System.out.println("Server is started");
while (true) {
Socket socket = serverSocket.accept();
try {
try (InputStream raw = socket.getInputStream()) { // ARM
System.out.println("=================BEFORE STARTING READING HEADER =======================");
System.out.println("Collecting data to string array...");
headerData = getHeaderToArray(raw);
//
System.out.println("+++++++++++++++++ AFTER ENDING READING HEADER +++++++++++++++++++++++");
System.out.println("Hello World");
}
} catch (MalformedURLException ex) {
System.err.println(socket.getLocalAddress() + " is not a parseable URL");
} catch (IOException ex) {
System.err.println(ex.getMessage());
}
}
} catch (Exception ex) {
System.out.println("error# " + ex.getMessage());
}
}
public static String getHeaderToArray(InputStream inputStream) {
String headerTempData = "";
// chain the InputStream to a Reader
Reader reader = new InputStreamReader(inputStream);
try {
int c;
while ((c = reader.read()) != -1) {
System.out.print((char) c);
headerTempData += (char) c;
if (headerTempData.contains("\r\n\r\n"))
break;
}
} catch (IOException ex) {
System.err.println(ex.getMessage());
}
headerData = headerTempData;
return headerTempData;
}
}

How to compile this network socket example in Java using Eclipse?

Okay, I found this example in the book, so I know that this code is error free. The program below contains two classes, both of them are main classes. One is for client and one is for server.
According to the book, I'm supposed to compile them like this:
Compile client and server and then start server as follows:
$ java GreetingServer 6066
Waiting for client on port 6066...
Check client program as follows:
$ java GreetingClient localhost 6066
Connecting to localhost on port 6066
Just connected to localhost/127.0.0.1:6066
Server says Thank you for connecting to /127.0.0.1:6066
Goodbye!
I want to be able to run them on eclipse, but every time I do so, it's giving me this error:
Exception in thread "main" java.lang.ArrayIndexOutOfBoundsException: 0
at GreetingServer.main(GreetingServer.java:47).
HOW CAN I RUN THIS PROGRAM IN ECLIPSE? Thanks.
// File Name GreetingClient.java
import java.net.*;
import java.io.*;
public class GreetingClient
{
public static void main(String [] args)
{
String serverName = args[0];
int port = Integer.parseInt(args[1]);
try
{
System.out.println("Connecting to " + serverName
+ " on port " + port);
Socket client = new Socket(serverName, port);
System.out.println("Just connected to "
+ client.getRemoteSocketAddress());
OutputStream outToServer = client.getOutputStream();
DataOutputStream out =
new DataOutputStream(outToServer);
out.writeUTF("Hello from "
+ client.getLocalSocketAddress());
InputStream inFromServer = client.getInputStream();
DataInputStream in =
new DataInputStream(inFromServer);
System.out.println("Server says " + in.readUTF());
client.close();
}catch(IOException e)
{
e.printStackTrace();
}
}
}
// File Name GreetingServer.java
import java.net.*;
import java.io.*;
public class GreetingServer extends Thread
{
private ServerSocket serverSocket;
public GreetingServer(int port) throws IOException
{
serverSocket = new ServerSocket(port);
serverSocket.setSoTimeout(10000);
}
public void run()
{
while(true)
{
try
{
System.out.println("Waiting for client on port " +
serverSocket.getLocalPort() + "...");
Socket server = serverSocket.accept();
System.out.println("Just connected to "
+ server.getRemoteSocketAddress());
DataInputStream in =
new DataInputStream(server.getInputStream());
System.out.println(in.readUTF());
DataOutputStream out =
new DataOutputStream(server.getOutputStream());
out.writeUTF("Thank you for connecting to "
+ server.getLocalSocketAddress() + "\nGoodbye!");
server.close();
}catch(SocketTimeoutException s)
{
System.out.println("Socket timed out!");
break;
}catch(IOException e)
{
e.printStackTrace();
break;
}
}
}
public static void main(String [] args)
{
int port = Integer.parseInt(args[0]);
try
{
Thread t = new GreetingServer(port);
t.start();
}catch(IOException e)
{
e.printStackTrace();
}
}
}
See these lines
public static void main(String [] args)
{
String serverName = args[0]; //<-- Expecting a value
int port = Integer.parseInt(args[1]); //<-- Expecting a value
The args[] is a string array containing arguments that you pass via command line. And when you try to run it from eclipse directly, you arent specifying these values which results in args[] to be an empty array and thus args[0] gives an ArrayIndexOutOfBoundsException
To solve this, either create a run configuration from within eclipse (see screenshot)
and specify arguements that you want eclipse to pass when running this class. YOu can do this by right-clicking the project, select run, then run-configurations --> double click on java_application and pass in the information that you want. You may need to specify the main class name when specifying arguments so that eclipse can recognize which main class to pass args to.
OR you can just hardcode these values directly in the class itself (for testing)
You need to create a run configuration and pass the arguments there. Run the program in eclipse. Let it fail. This automatically creates a run configuration. Edit the configuration to add parameters. Or create a new run configuration.

java.net.BindException: Permission denied when creating a ServerSocket on Mac OSX

I Tried to run a Java socket in mac with eclipse but it doesn't work. I got this error:
Exception in thread "main" java.net.BindException: Permission denied
at java.net.PlainSocketImpl.socketBind(Native Method)
at java.net.PlainSocketImpl.socketBind(PlainSocketImpl.java:521)
at java.net.PlainSocketImpl.bind(PlainSocketImpl.java:414)
at java.net.ServerSocket.bind(ServerSocket.java:326)
at java.net.ServerSocket.<init>(ServerSocket.java:192)
at java.net.ServerSocket.<init>(ServerSocket.java:104)
at server.MessageServer.main(MessageServer.java:11)
How can i make it to run?
package server; //ChatServer
import java.io.*;
import java.net.*;
public class MessageServer {
public static void main (String args[]) throws IOException {
int port = 100;
ServerSocket server = new ServerSocket (port);
System.out.println("Server is started!");
while (true) {
Socket client = server.accept ();
System.out.println ("Accepted from " + client.getInetAddress ());
MessageHandler handler = new MessageHandler (client);
handler.start();
}
}
}
You can't open a port below 1024, if you don't have root privileges and from the code you posted in your comment, you seem to be trying to open port 100 which confirms my theory.
You need to use a port which is higher than 1024, if you're running the code under a non-root user.
Unix-based systems declare ports < 1024 as "privileged" and you need admin rights to start a server.
For testing, use a port number >= 1024.
When deploying the server in production, run it with admin rights.
I had the same issue and my port numbers were below 1024 changing port number to above 1024 solved my problem. Ports below 1024 are called Privileged Ports and in Linux (and most UNIX flavors and UNIX-like systems), they are not allowed to be opened by any non-root user.
Many systems declare ports that are less than 1024 as "admin rights" ports. Meaning, if you're only using this for basic testing use a higher port such as 2000. This will clear the exception that you're getting by running your current program.
int port = 100;
ServerSocket server = new ServerSocket (port);
Change that to something such as:
int port = 2000;
ServerSocket server = new ServerSocket (port);
MyServer.java
import java.io.*;
import java.net.*;
public class MyServer
{
ServerSocket ss;
Socket s;
DataOutputStream dos;
DataInputStream dis;
public MyServer()
{
try
{
System.out.println("Server Started ");
ss=new ServerSocket(4444);
s=ss.accept();
System.out.println(s);
System.out.println("Client Connected");
dis=new DataInputStream(s.getInputStream());
dos=new DataOutputStream(s.getOutputStream());
ServerChat();
}
catch(Exception e)
{
System.out.println(e);
}
}
public static void main(String arg[])
{
new MyServer();
}
public void ServerChat()throws IOException
{
String str;
do
{
str=dis.readUTF();
System.out.println("Client msg : "+str);
dos.writeUTF("Hello "+str);
dos.flush();
}while(!str.equals("stop"));
}
}
MyClient.java
import java.io.*;
import java.net.*;
public class MyClient
{
Socket s;
DataInputStream din;
DataOutputStream dout;
public MyClient()
{
try
{
s=new Socket("localhost",4444);
System.out.println(s);
din = new DataInputStream(s.getInputStream());
dout = new DataOutputStream(s.getOutputStream());
ClientChat();
}
catch(Exception e)
{
System.out.println(e);
}
}
public void ClientChat() throws IOException
{
BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
String s1;
do
{
s1=br.readLine();
dout.writeUTF(s1);
dout.flush();
System.out.println("Server Msg : "+din.readUTF());
}while(!s1.equals("stop"));
}
public static void main(String arg[])
{
new MyClient();
}
}
Run Server program with root (Administrator).
Windows: Run as Administrator the IDE/Editor.
Ubuntu/macOS: sudo java...
This is an old question, and I might be replying too late, but I would like to anyways share my experience in case anyone hits the issue.
I was using port# 8000, but still unable to bind to the port from a java program. It was network filter running as part of eset endpoint security that was blocking the connection.
I added a rule in eset firewall to allow port 8000, and it started working.

Running Socket Programming code in Eclipse

I have written a program on Socket Programming, and I created a client and a server. Codes for both are as follows:
CLIENT:
import java.net.*;
import java.io.*;
public class GreetingClient
{
public static void main(String [] args)
{
String serverName = args[0];
int port = Integer.parseInt(args[1]);
try
{
System.out.println("Connecting to " + serverName
+ " on port " + port);
Socket client = new Socket(serverName, port);
System.out.println("Just connected to "
+ client.getRemoteSocketAddress());
OutputStream outToServer = client.getOutputStream();
DataOutputStream out =
new DataOutputStream(outToServer);
out.writeUTF("Hello from "
+ client.getLocalSocketAddress());
InputStream inFromServer = client.getInputStream();
DataInputStream in =
new DataInputStream(inFromServer);
System.out.println("Server says " + in.readUTF());
client.close();
}catch(IOException e)
{
e.printStackTrace();
}
}
}
SERVER:
import java.net.*;
import java.io.*;
public class GreetingServer extends Thread
{
private ServerSocket serverSocket;
public GreetingServer(int port) throws IOException
{
serverSocket = new ServerSocket(port);
serverSocket.setSoTimeout(10000);
}
public void run()
{
while(true)
{
try
{
System.out.println("Waiting for client on port " +
serverSocket.getLocalPort() + "...");
Socket server = serverSocket.accept();
System.out.println("Just connected to "
+ server.getRemoteSocketAddress());
DataInputStream in =
new DataInputStream(server.getInputStream());
System.out.println(in.readUTF());
DataOutputStream out =
new DataOutputStream(server.getOutputStream());
out.writeUTF("Thank you for connecting to "
+ server.getLocalSocketAddress() + "\nGoodbye!");
server.close();
}catch(SocketTimeoutException s)
{
System.out.println("Socket timed out!");
break;
}catch(IOException e)
{
e.printStackTrace();
break;
}
}
}
public static void main(String [] args)
{
int port = Integer.parseInt(args[0]);
try
{
Thread t = new GreetingServer(port);
t.start();
}catch(IOException e)
{
e.printStackTrace();
}
}
}
Now, I am unable to run the program in Eclipse, can anyone help me, how to do this ?
Go to RunConfigurations.. and click on the Class Name(as here 'GreetingClient') under the java application in the left pane of RunConfiguration window
on the right side you will get many tab like Main,Arguments,jre,ClassPath etc so now click on the 'Arguments'
below this tag you will get textbox with label Program arguments:
here in this textbox you need to pass your command line argument
for multiple values give single space between the argument values then click on the Apply button
like in above case you need to pass commandline argument twice.
so first you configure for the GreetingServer and then for the GreetingClient and then apply and run one by one
click on the GreetingServer.java and then right click on mouse and select Run As-->Run Configuration.. then go to Java Application and click
GreetingServer -->Argument--> 6000 -->apply and -->run
output like this
Waiting for client on port 6000...
now click on the GreetingClient.java and then right click on mouse and select Run As-->Run Configuration.. then go to Java Application and click
GreetingClient -->Argument--> 127.0.0.1 6000 -->apply and -->run
then you will get your application running and
output like this
Connecting to 127.0.0.1 on port 6000
Just connected to /127.0.0.1:6000
Server says Thank you for connecting to /127.0.0.1:6000
Goodbye!
Any port you can send it your wise just keep in mind port no. should be free
for the eclipse argument passing you can go through this link
Actually, you need to run the programs individually in the
Eclipse-IDE. The output will be indented one on another in next tab on
the output area.
I don't have info about Eclipse.
In Netbeans,you need to run the Client.java file separately. Then,move
to Server.java file and run it separately. You'll see at the bottom
that two windows---one running Client.java and the other running
Server.java will be running independently. Now,send message from
client to server and vice-versa.
EDIT FOR YOUR COMMAND LINE PARAMETER SETTING IN ECLIPSE IDE :-
Go to Project--> Run --> Run Configurations --> Arguments.!
Pass the arguments as
args[0]=127.0.0.1 //local-host
args1=3000 //say 3000,you can give any port no. but take care that it should exist!
Try running the Client program first and then run the server program in Netbeans, the program will run with no problem...
/*Server*/
import java.net.*;
import java.io.*;
public class MyServer
{
public static void main(String args[])throws Exception
{
ServerSocket ss=new ServerSocket(8100);
Socket s=ss.accept();
DataInputStream din=new DataInputStream(s.getInputStream());
DataOutputStream dout=new DataOutputStream(s.getOutputStream());
BufferedReader br=new BufferedReader(new InputStreamReader(System.in));
String str="",str2="";
while(!str.equals("stop"))
{
str=din.readUTF();
System.out.println("clint Says"+str);
str2=br.readLine();
dout.writeUTF(str2);
dout.flush();
}
din.close();
s.close();
ss.close();
}
}

Trying to get a java socket program to work, but getting "java.net.BindException: Address already in use 6666 "

Here is the code
I have written a server and client. But when i run them, (as you can see in the last program), I get the following error:
Whoop s! java.net.BindException: Address already in use 6666
6666 is the port no. i specified.
import java.net.*;
import java.io.*;
import java.lang.*;
public class processSendHelper
{
Process p;
String address;
int port;
long msg_data;
processSendHelper(int pid, int current_round, long address, long msg_data, int port)
{
try
{
ServerSocket sSoc = new ServerSocket(port);
Socket inSoc = sSoc.accept();
msg_Thread msgT = new msg_Thread(inSoc, msg_data);
msgT.start();
Thread.sleep(5000);
sSoc.close();
}
catch(Exception e)
{
System.out.println("Whoop s! " + e.toString());
}
}
}
/* sends out (or rather just makes available) the provided msg
* */
class msg_Thread extends Thread
{
Socket threadSoc;
long msg_data;
msg_Thread (Socket inSoc, long msg_data)
{
threadSoc = inSoc;
this.msg_data = msg_data;
}
public void run()
{
try
{
PrintStream SocOut = new
PrintStream(threadSoc.getOutputStream());
SocOut.println(msg_data);
}
catch (Exception e)
{
System.out.println("Whoops!" + e.toString());
}
try
{
threadSoc.close();
}
catch (Exception e)
{
System.out.println("Oh no! " +
e.toString());
}
}
}
import java.net.*;
import java.io.*;
public class processReceiveHelper
{
Socket appSoc;
BufferedReader in;
String message;
String host;
int port;
processReceiveHelper(String host,int port)
{
try
{
appSoc = new Socket(host,port);
in = new BufferedReader(new InputStreamReader(appSoc.getInputStream()));
message = in.readLine();
System.out.println(message);
/* Tokenizer code comes here
* Alongwith the code for
* updating the process object's
* data
* */
}
catch (Exception e)
{
System.out.println("Died... " +
e.toString());
}
}
}
public class Orchestrator
{
public static void main(String[] args)
{
processSendHelper psh = new processSendHelper(1, 2, 1237644, 6666, 2002);
processReceiveHelper prh = new processReceiveHelper("localhost", 2002);
}
}
EDIT:
I found the problem. The reason was that i was running both the server and client from the same main program.
the following worked:
That means there is already an application operating on port 6666 preventing your Java application using it. However, it is equally possible there is a running process of your Java application still holding onto 6666. Terminate any running java processes and try re-running the code - if it still fails then you have some other application using 6666 and you would be better using a different port.
That means that the port 6666 is already being used. There are two main causes/solutions for this:
Some other program is using that port. Solution: Choose a different port.
Your old Java program is hanging and still "using" that port. Close all of your hanging Java programs and try again. If that doesn't solve your problem, choose a different port.
Does it happen when you run the program for the second time? You may want to setReuseAddress(true) on this socket.

Categories