The constructor ServerSocket(int) is undefined - java

I am new at JAVA basically I do code in C++. Recently I needed to do something in JAVA socket programming. But I am getting a strange error in ServerSocket(..). I am trying to create a server socket in a particular port. For that my code is like below.
import java.net.*;
import java.io.*;
import java.util.*;
public class ServerSocket {
static ServerSocket socket1;
protected final static int port = 19999;
static Socket connection;
public static void main(String[] args) {
try
{
socket1 = new ServerSocket(port);
}
catch (IOException e) {}
}
}
But I am getting compilation error "The constructor ServerSocket(int) is undefined". Thanks.

Please see my second comment to your original question:
Also, do you have your own class named ServerSocket?
You've named your class ServerSocket and so the Java compiler is looking for the constructor in this class, one that takes an int. Rename that class so you don't have a name conflict and now can use the Java core ServerSocket class.

I suggest a java tutorial first. Just to learn the basic differences.
In short:
In Java everything has to be in a class. You define a static method named 'main'. This is the start of your application.
Here is your example (Filename: DemoClass.java):
import java.net.*;
import java.io.*;
public class DemoClass {
private static ServerSocket socket1;
private static final int port = 19999;
private static void handleConnection(Socket socket) throws IOException {
OutputStream out = socket.getOutputStream();
// Say hello
out.write("Hello World\n".getBytes());
out.flush();
// Close the connection
out.close();
socket.close();
}
// Use this exact method signature!
public static void main(String[] args) {
try {
socket1 = new ServerSocket(port);
// Here is some example what you could do
Socket connection = socket1.accept();
handleConnection(connection);
} catch(IOException e) {
// What should be done if this fails? E.g. port already in use
e.printStackTrace();
}
}
}
But I really suggest a Java and a Java Socket tutorial.
Greetings!

The server program creates the ServerSocket object in a try-with-resources statement:
import java.io.*;
import java.net.*;
class Test{
private static ServerSocket socket1;
private final static int port = 19999;
public static void main (String [] args){
try{
socket1 = new ServerSocket(port);
}
catch(IOException e){
e.printStackTrace();
}
}
}
The constructor for ServerSocket throws an exception if it can't listen on the specified port. for example, the port is already being used.

Related

Parallel processing in Java Sockets not working properly

I have made two different programs for port Scanning. Both the programs use Threads but the thread distribution is different.
The first one uses single thread for single port, so it is not optimized for memory and time.
Here is the code :
import java.net.Socket;
import java.util.Scanner;
import java.lang.Exception;
import java.lang.Thread;
class helper{
public static void main(String []args){
Scanner s= new Scanner(System.in);
int port;
System.out.print("Enter web url :");
String url = s.next();
for(port=0;port<65536;port++){
helper2 h = new helper2(url,port);
h.start();
}
s.close();
}
}
class helper2 extends Thread{
int port;
String url;
helper2(String url,int port){
this.url=url;
this.port=port;
}
private void getStatus(){
try{
Socket skt = new Socket(url,port);
System.out.println(port);
skt.close();
}catch(Exception e){
//Handle Exception here
}
}
public void run(){
getStatus();
}
}
But in the other one I have 256 threads each having performing over 256 ports. It is faster.
Here is the other one :
import java.net.Socket;
import java.lang.Thread;
import java.util.Scanner;
import java.lang.Exception;
class helper {
public static void main(String []args){
Scanner s = new Scanner(System.in);
System.out.printf("Enter url :");
String url = s.next();
for(int i=0;i<256;i++){
helper2 h = new helper2(url,256*i);
h.start();
}
s.close();
}
}
class helper2 extends Thread {
int port ;
String url ;
helper2(String url, int port){
this.port=port;
this.url=url;
}
public void run(){
for(int i=0;i<256;i++){
try {
Socket skt = new Socket(url,i+port);
System.out.println(port+i);
skt.close();
} catch (Exception e) {
//TODO: handle exception
// System.out.print('j'); //for debugging
}
}
}
}
Both are working fine when url is given as localhost. But for other url like www.google.com second program does not behave correctly. Sometimes it does not produce any output and sometimes it throws OutOfMemory error and unable to create more threads. Please help.
Socket(String, int) tries to connect immediately, with no timeout (which means that it waits infinitely if the connection is not accepted by the server). At some hosts (including google.com), a connection to ports that are not specifically open will not be rejected automatically; instead, an attempt of such a connection will hang for some time, until it reaches a client-defined timeout (which is infinite in the case of Socket(String, int)).
I'd use Socket() constructor which does not connect automatically, and then connect manually passing some finite timeout:
Socket socket = new Socket();
socket.connect(new InetSocketAddress("google.com", 8888), 3000);

How to close a server port after we are done using it?

Note: I found a similar question here:
How to close port after using server sockets
But did not find any satisfactory answer there.
Here is my code for the client program:
package hf;
import java.io.*;
import java.net.*;
public class DailyAdviceClient
{
private static final int chatPort = 4242;
public static void main(String[] args)
{
DailyAdviceClient client = new DailyAdviceClient();
client.go();
}
private void go()
{
try
{
Socket socket = new Socket("127.0.0.1",chatPort);
InputStreamReader inputStream = new InputStreamReader(socket.getInputStream());
BufferedReader bufferedReader = new BufferedReader(inputStream);
String advice = bufferedReader.readLine();
System.out.println("Advice received by the client for today is "+advice);
bufferedReader.close();
}
catch(Exception e)
{
System.out.println("Failed to connect to the server");
}
}
}
And here is the code for the server program:
package hf;
import java.io.*;
import java.net.*;
public class DailyAdviceServer
{
private String[] adviceList = {"Take smaller bites",
"Go for the tight jeans. No they do NOT make you look fat.",
"One word: inappropriate",
"Just for today, be honest. Tell your boss what you *really* think",
"You might want to rethink that haircut."};
private static final int chatPort = 4242;
public static void main(String[] args)
{
DailyAdviceServer server = new DailyAdviceServer();
server.go();
}
private void go()
{
try
{
ServerSocket serverSocket = new ServerSocket(chatPort);
while(true)
{
Socket socket = serverSocket.accept();
PrintWriter writer = new PrintWriter(socket.getOutputStream());
String advice = getTodaysAdvice();
writer.println(advice);
writer.close();
}
}
catch(Exception e)
{
System.out.println("Error in establishing connection with the client");
}
}
private String getTodaysAdvice()
{
String advice = null;
int randomIndex = (int) (Math.random()*adviceList.length);
advice = adviceList[randomIndex];
return advice;
}
}
In the application, whenever a client program connects to the server program, it receives a String that contains advice for the day.
When I run
netstat -an
In the command prompt of my Windows computer as suggested in one of the answers in the aforementioned link, I get a message that the port 4242 is
LISTENING
How do I close the port and make it available for future re-use?
To get rid of the LISTENING port you have to call serverSocket.close().
You have to use socket.close() after closing the writer and bufferedReader. So the Port will be free for another communication.

Asynchronous socket handling in java using the conccurent package still blocks code?

I'm trying to play around with the concurrent package and for this reason I tried to write a simple socket handler. Here is the code:
import java.io.*;
import java.net.*;
import java.util.*;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
public class MultiThreadedServer{
private final static int number_of_threads = 4;
private final static int port = 1134;
public static void main(String[] args){
try{
ServerSocket ss = new ServerSocket(port);
ExecutorService pool = Executors.newFixedThreadPool(number_of_threads);
for(;;){
pool.execute(new SocketHandler(ss.accept()));
}
}catch(Exception e){
System.out.println(e.toString());
}
}
}
class SocketHandler implements Runnable {
private Socket socket;
SocketHandler(Socket s){
this.socket = s;
System.out.println("-- Socket has connected -- ");
}
public void run(){
try{
BufferedReader reader = new BufferedReader(new InputStreamReader(socket.getInputStream()));
String s = "";
while((s = reader.readLine()) != null ){
System.out.println(s);
}
}catch(Exception e){
System.out.println(e.toString());
}
}
}
This code ^^ simply waits for sockets and reads whatever the socket sends. It works fine to an extent. ( I will explain a bit later what bothers me).
The following code is the sender class which "sends" a socket
import java.io.*;
import java.net.*;
public class Sender{
public static void main(String args[]){
try{
int port = Integer.parseInt(args[0]);
Socket socket = new Socket(InetAddress.getByName(null),port);
PrintWriter writer = new PrintWriter(socket.getOutputStream());
writer.write("Wohoo!");
writer.close();
}catch(Exception e){
System.out.println(e.toString());
}
}
}
The code compiles fine and it even runs fine when I run my sender. However if I type
java Sender
about 3 times a second and I try to run it into my console the following thing gets printed:
java.net.BindException: Address already in use
However the whole point of this code was to not block the connections to my port and to queue the tasks. How can I tackle this?
See my comment. But I think what you are seeing is exhausting your tcp ports. Are you running this thing for awhile before it starts printing port already in use? If so read ahead.
So after closing a socket there is a state of TIME_WAIT. Until it passes, you cannot reuse same port unless you have set the socket option SO_REUSEADDR.
So you need to use that option perhaps. See this answer for more insight:
https://stackoverflow.com/a/14388707/520567

Java - running multiple clients with eclipse

I've got codes of a server and clients written on Java. But the question is how to run multiple clients on DIFFERENT console-windows with Eclipse when server is running? Thx for helping!
(solved!!)
UPDATE**
Another question: I'll create a new question
Server:
import java.net.*;
import java.io.*;
public class ATMServer {
private static int connectionPort = 8989;
public static void main(String[] args) throws IOException {
ServerSocket serverSocket = null;
boolean listening = true;
try {
serverSocket = new ServerSocket(connectionPort);
} catch (IOException e) {
System.err.println("Could not listen on port: " + connectionPort);
System.exit(1);
}
System.out.println("Bank started listening on port: " + connectionPort);
while (listening)
new ATMServerThread(serverSocket.accept()).start();
serverSocket.close();
}
}
ServerThread:
import java.io.*;
import java.net.*;
public class ATMServerThread extends Thread {
private Socket socket = null;
private BufferedReader in;
PrintWriter out;
public ATMServerThread(Socket socket) {
super("ATMServerThread");
this.socket = socket;
}
public void run(){
}
}
}
Client: (**UPDATE)
import java.io.*;
import java.net.*;
import java.util.Scanner;
public class ATMClient {
private static int connectionPort = 8989;
public static void main(String[] args) throws IOException {
Socket ATMSocket = null;
PrintWriter out = null;
BufferedReader in = null;
String adress = "";
try {
adress = "127.0.0.1";
} catch (ArrayIndexOutOfBoundsException e) {
System.err.println("Missing argument ip-adress");
System.exit(1);
}
try {
ATMSocket = new Socket(adress, connectionPort);
out = new PrintWriter(ATMSocket.getOutputStream(), true);
in = new BufferedReader(new InputStreamReader
(ATMSocket.getInputStream()));
} catch (UnknownHostException e) {
System.err.println("Unknown host: " +adress);
System.exit(1);
} catch (IOException e) {
System.err.println("Couldn't open connection to " + adress);
System.exit(1);
}
out.close();
in.close();
ATMSocket.close();
}
You can run as many socket clients from Eclipse provided that you pass user-defined ip/port info as command arguments from main() under Program Arguments tab in Run Configuration dialog for that program inside Eclipse rather than using some hardwired values for ip/port.
To create multiple console views (via separate Console View tabs rather than clicking on each instance), you need to create a new console view for each target instance in Eclipse Debug View mode; to achieve this, you need to select "New Console View" (from the icon button with the plus symbol to the far right of the Console View) and assign which program instance to view from each new console.
Another question: if I have to change something on ServerThread, for example, add a title, is that possible to execute that without restart the server?
Which title? I don't see any GUI code for the ServerThread code snippet. Do you mean the title name of the Console view tab?

Help me to fix a bug in this thread example

I am trying to create a thread to simply send the text to client. However, if you copy this code to IDE, you will see that there is a red underline under client.getOutputStream(). I do not know what is wrong here. The IDE says "Unhandled exception type IOException". Could anybody tell me?
import java.io.BufferedReader;
import java.io.InputStreamReader;
import java.io.PrintWriter;
import java.net.Socket;
import java.util.ArrayList;
import java.util.List;
public class ServerStudentThread extends Thread {
Socket client;
public ServerStudentThread(Socket x) {
client = x;
}
public void run() {
// create object to send information to client
PrintWriter out = new PrintWriter(client.getOutputStream(),true);
out.println("Student name: ");//send text to client;
}
}
For reference, here is the code that calls the thread.
import java.io.*;
import java.net.*;
import java.util.*;
public class Server2 {
public static void main(String args[]) throws Exception {
int PORT = 5555; // Open port 5555
//open socket to listen
ServerSocket server = new ServerSocket(PORT);
Socket client = null;
while (true) {
System.out.println("Waiting for client...");
// open client socket to accept connection
client = server.accept();
System.out.println(client.getInetAddress()+" contacted ");
System.out.println("Creating thread to serve request");
ServerStudentThread student = new ServerStudentThread(client);
student.start();
}
}
}
It's probably that getOutputStream() can throw an exception and you're not catching it, try putting a try / catch (IOException e) around the block of code.
public void run() {
try {
// create object to send information to client
PrintWriter out = new PrintWriter(client.getOutputStream(),true);
out.println("Student name: ");//send text to client;
} catch (IOException e) {
throw new RuntimeException("It all went horribly wrong!", e);
}
}
So you need to add a try/catch block to handle the I/O exception.
Read the section on Exceptions from the Java tutorial.
From the javadoc:
public OutputStream getOutputStream() throws IOException
IOException is a checked exception. You need to use a try/catch block to handle that possibility.
Kalla,
You need to either put the line in between try/catch block or declare run to throw IOException

Categories