Skip to Main Content

New to Java

Announcement

For appeals, questions and feedback about Oracle Forums, please email oracle-forums-moderators_us@oracle.com. Technical questions should be asked in the appropriate category. Thank you!

how to use a Singleton to open a TCP port

843785Feb 2 2009 — edited Feb 2 2009
I have an existing demo application that displays some text data. I would like to modify the demo the open a TCP socket (as a server) and respond to requests from a client to send the text data. I attempted to implement this using a Singleton class, but I am unsure how to implement the methods to send the data from the server back to the client. I am attaching the code that I have so far.

I would appreciate any suggestions for how to pass the data back to the client. Specifically, I am confused about how to call the singleton. (What do I have to do on the server side to use this class and how can I test on the client side?)


import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.PrintWriter;
import java.net.BindException;
import java.net.ServerSocket;
import java.net.Socket;

public class ProjectXSingleton {
private static ProjectXSingleton uniqueInstance;
static ServerSocket server;

private ProjectXSingleton () {
}

public static ProjectXSingleton getInstance() {
if (uniqueInstance == null) {
uniqueInstance = new ProjectXSingleton();

//establish socket conncection
try {
ServerSocket server = new ServerSocket(7777);
Socket incoming = server.accept();

BufferedReader in = new BufferedReader(new InputStreamReader(
incoming.getInputStream()));
PrintWriter out = new PrintWriter(incoming.getOutputStream(), true /* autoFlush */);

boolean done = false;
while (!done) {
String line = in.readLine();
if (line == null)
done = true;
else {
out.println("Echo: " + line);

if (line.trim().equals("BYE"))
done = true;
}
}
incoming.close();
} catch (IOException e) {
System.out.println("IOException on socket listen: " +e);
e.printStackTrace();
}
}
return uniqueInstance;
}

public void writeToProjectX(String str) {
*//I AM UNSURE WHAT THE SIGNATURE OF THIS METHOD SHOULD LOOK*
*//LIKE AND HOW TO CALL IT*
System.out.println("WRITE THIS:" +str);
}


}
Comments
Locked Post
New comments cannot be posted to this locked post.
Post Details
Locked on Mar 2 2009
Added on Feb 2 2009
3 comments
1,067 views