I have created a program that simply has a server which connects the port (6789) and a client when connects to this same port. However, my issue begins with having the server start and connect to port 6789.
The interesting thing is that my server works perfectly in Eclipse, however when it is embedded in HTML, it does not work although the GUI and other functionalities work. The following code is for starting up my server. I have not included the ClientThread or ServerGUI class since my main issue is getting the server to connect to the port anyways.
Is there another port I should be using instead of 6789 when on HTML?
Thank you!
public class Server {
private ServerGUI sg;
private int port;
// the boolean that will be turned of to stop the server
private boolean keepGoing;
HashSet<String> retailers;
HashSet<String> retailers_company;
ArrayList<HashSet<String>> al;
public Server(int port, ServerGUI sg) {
this.sg = sg;
this.port = port;
}
public void start() {
keepGoing = true;
try
{
ServerSocket serverSocket = new ServerSocket(port);
display("Server started on Port: " + port);
while(keepGoing)
{
Socket socket = serverSocket.accept();
if(!keepGoing)
break;
ClientThread t = new ClientThread(socket);
t.start();
}
try {
serverSocket.close();
}
catch(Exception e) {
display("Exception closing the server and clients: " + e);
}
}
// something went bad
catch (IOException e) {
display("Exception on new ServerSocket: " + e + "\n");
}
}
}
Related
I am trying to open a socket inside a bukkit plugin so i could send data to it using php or node but instead of socket remaining open after one use it just closes and also server does not load before this happens what should i do i am out of ideas.
Main:
public class Main extends JavaPlugin {
public void onEnable() {
saveDefaultConfig();
getConfig().options().copyDefaults(true);
System.out.println("[INFO] Main class loaded.");
start();
}
public void start() {
SocketServer server = new SocketServer();
try {
server.start(getConfig().getInt("port"), getConfig().getString("socket-password"));
System.out.println("[INFO] Main successfully called start.");
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
Socket server class:
When called this should read information convert it into array check the first item in array and use it as auth code then array should be converted into string and used in Command executor class. This works fine but after one use this just closes
public class SocketServer {
private ServerSocket serverSocket;
private Socket clientSocket;
private PrintWriter out;
private BufferedReader in;
public void start(int port, String socketpwd) throws IOException {
System.out.println("[INFO] Socket server listening on: " + port);
serverSocket = new ServerSocket(port);
clientSocket = serverSocket.accept();
out = new PrintWriter(clientSocket.getOutputStream(), true);
in = new BufferedReader(new InputStreamReader(clientSocket.getInputStream()));
Boolean enabled = true;
try {
// Socket authentication
String message = in.readLine();
String suffix[] = message.split(" ");
System.out.println("Socket auth code used: "+ suffix[0]);
System.out.println("Socket pwd is: " + socketpwd);
if (socketpwd.equals(suffix[0])) {
out.println("Auth sucessfull!");
// do the following command from args here
String command = suffix[1];
int suffixL = suffix.length;
// add arguments to command
for (int i = 2; i < suffixL; i++) {
command = command + " " + suffix[i];
}
// call req exec
System.out.println("[INFO] Socket server contacted Request executor with: " + command);
RequestExecutor.executor(command);
enabled = false;
}
else {
out.println("Unrecognised auth code!");
}
} catch (NullPointerException e) {
System.out.println("Exception prevented!");
}
}
public void stop() throws IOException {
in.close();
out.close();
clientSocket.close();
serverSocket.close();
}
}
Other problem as i mentioned is that bukkit server does not fully load before one request has been made to this socket.
Thank you for your help.
First of all you shouldn't be running a socket like that on the main thread, typically you should be running this on an async task using the Bukkit scheduler.
Then once you open the socket you should create a while loop to continuously poll for a connection and handle the incoming data. Instead what you are doing is opening the socket, reading a line and then dropping the connection.
You want to be doing something similar to
while(true){
Socket socket = serverSocket.accept();
}
See this webpage for some more info.
I am trying to write a simple TCP server, but the problem I have is that the socket gets closed after the first run (it's running in a thread, by the way). I could try rewriting it without ARM (Automatic Resource Management), that bock in round squares after try - but I would rather keep it.
So, it there a way to write a simple persistent TCP server by using ARM in Java?
public class Server {
/* Server */
public int port = 8088;
public Server (int port){
this.port = port;
System.out.println("Will listen on port " + this.port);
}
public Server () {
System.out.println("Will listen on default port " + port);
}
public void start() {
try (ServerSocket initSocket = new ServerSocket(port);
Socket socket = initSocket.accept();
BufferedReader bfin =
new BufferedReader(new InputStreamReader(socket.getInputStream()));
BufferedOutputStream bfout =
new BufferedOutputStream(socket.getOutputStream())
)
{
String line = bfin.readLine();
while (line != null && !"BYE\n".equals(line)){
String answer = parseadd(line) + "\n";
System.out.println("From client: " + line);
bfout.write(answer.getBytes());
bfout.write("BYE\n".getBytes());
bfout.flush();
line = bfin.readLine();
}
System.out.println("Exiting server while loop!");
}
catch (IOException e) {
System.out.println("Exception caught when trying to");
System.out.println(e.getMessage());
}
}
}
An RMI Program is running on a remote machine(RMI Server), We invoked this program through the Web app(RMI client). When the RMI client invokes the RMI Server, the server instantiate a program and the result is send back to client through the simple network client code. The sample code as below.
RMI server code
try {
if(monitor == null) return;
monitor.stop();
SimpleClient sc=new SimpleClient(client,1131,"`file Monitor stopped");
//System.out.println("---aaaaa---");
sc.sendMsg();
System.out.println("Monitor stopped");
}catch(Exception ex){
ex.printStackTrace();
}
RMI Client code
public static List plusOne003Test(String ipAddress, boolean isstopped) {
ArrayList alist = null;
try {
System.out.println("All Plus one....plusOne003Test");
Class testClass = Class.forName("PlusOneClient11");
System.out.println("class Name::::::>"+testClass.getName());
Method testMethod = testClass.getMethod("plusOne003Test",
new Class[] { String.class,boolean.class});
alist = (ArrayList) testMethod.invoke(testClass.newInstance(),ipAddress,isstopped);
//System.out.println("ALIST::::::>"+alist);
System.out.println("before create server");
SimpleServer t=new SimpleServer(1131);
t.start();
Thread.sleep(10000);
System.out.println("after create server");
System.out.println("test3:::>" + alist.size());
} catch (Exception ex) {
ex.printStackTrace();
}
return alist;
}
network code for received the message from the RMI Server
public class SimpleServer extends Thread{
private ServerSocket serverSocket;
public SimpleServer(int port) throws IOException {
try{
ServerSocketFactory ssf=ServerSocketFactory.getDefault();
serverSocket=ssf.createServerSocket(port);
}catch(BindException be){
be.printStackTrace();
}
}
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());
String rec=in.readUTF();
System.out.println("\n"+rec+"\n");
if(rec.contains("`")){
String rec1[]=rec.split("`");
**JOptionPane.showMessageDialog(null, rec1[0]+"\n"+rec1[1]);**
----------------------------------------------------------------
System.out.println("\n"+rec+"\n");
}
}catch(SocketTimeoutException s)
{
s.printStackTrace();
System.out.println("Socket timed out!");
break;
}catch(IOException e)
{
e.printStackTrace();
break;
}
}
}
}
The code JOptionPane.showMessageDialog(null, rec1[0]+"\n"+rec1[1]); message needs to be displayed in the web app alert message.
You need to understand the difference between server side (JSP, Servlet) and client side (HTML, Javascript) code in this case. JSP is used to generate the HTML code, i.e. it runs on the server, generates the HTML that is sent to browser, and then stops. So it is not possible to put any messaging client's code into the JSP.
Basically, the web technology is a request-response technology, the communication is initiated by the client. But there are of course ways to implement also a server-initiated communication. I would recommend you to have a look at HTML5 WebSockets (e.g. http://www.oracle.com/webfolder/technetwork/tutorials/obe/java/HomeWebsocket/WebsocketHome.html), which should be the most standard way to implement such functionality.
I just recently found the ServerSocket and Socket class found in the Java library and so I wanted to make a simple messaging app. The purpose of the app is to be able to communicate with someone on a different network than mine (I am the server side and have my own client side).
Here is the Messenger_Server.java's connecting method
public static void main (String [] args)throws IOException{
InetAddress ip;
try{
final int PORT = 444;
ip = InetAddress.getLocalHost();
ServerSocket server = new ServerSocket(PORT);
System.out.println("Waiting for clients...");
System.out.println(server.getInetAddress() + " " + ip.getHostAddress());
while(true){
Socket sock = server.accept();
connectionArray.add(sock);
System.out.println("Client connected from " + sock.getLocalAddress().getHostName());
addUserName(sock);
Messenger_Server_Return chat = new Messenger_Server_Return(sock);
Thread X = new Thread(chat);
X.start();
}
} catch(Exception e) {
e.printStackTrace();
}
}
Here is the client's connecting method from Messenger_Client.java
public static void connect(){
try{
final int PORT = 444;
// the ip below is the one i get as my ipv4
Socket sock = new Socket ("10.122.***.***",PORT);
System.out.println("you be connected to: " + InetAddress.getByAddress(InetAddress.getLocalHost().getAddress()));
chatClient = new Messenger_Client(sock);
PrintWriter out = new PrintWriter(sock.getOutputStream());
out.println(userName);
out.flush();
Thread X = new Thread(chatClient);
X.start();
}catch (Exception X){
X.printStackTrace();
JOptionPane.showMessageDialog(null, "Server not responding.");
System.exit(0);
}
}
So I gave the client side of the program to my friend and he said the host could not be found. Which IP should I use so my friend can connect to my ServerSocket, and could there be anything limiting my friend from connecting to me?
I am trying to create a simple web proxy app using Java(without using the HTTPUrlConnection class).
I have so far managed to successfully have my server listen on port 10000, and then accept a client connection when I enter a URL into my browser.
I now require my proxy to forward the HTTP request from the browser to the actual web server(the URL which I typed into the browser).
However, I am getting a java.net.UnknownHostException: when attempting to create a socket connection between my proxy and the web server. Does anyone know what may be causing this issue?
Below is the output showing the error aswell as the complete code aswell. Any help is very much appreciated!
Starting the socket server at port:10000
Listening.....
Socket[addr=/127.0.0.1,port=64099,localport=10000]has connected
URL IS http://www.hotmail.com
Can't connect
java.net.UnknownHostException: http://www.hotmail.com
import java.net.*;
import java.io.*;
public class Proxy {
private ServerSocket serverSocket;
private int port;
public Proxy(int port) {
this.port = port; }
public static void main(String[] args) {
int port = 10000;
try {
// initialize the proxy
Proxy proxy = new Proxy(port);
proxy.start();
}
catch (IOException e) {
e.printStackTrace();
}
}
public void start() throws IOException {
System.out.println("Starting the socket server at port:" + port);
serverSocket = new ServerSocket(port);
//Listen for client connection
System.out.println("Listening.....");
Socket client = serverSocket.accept();
//A client has connected to this server
verifyClient(client);
}
private void verifyClient(Socket client) throws IOException {
System.out.println(client + "has connected");
BufferedReader in = new BufferedReader(new InputStreamReader(client.getInputStream()));
//Parse the HTTP request from the browser and find the URL
String request;
while ((request = in.readLine()) != null) {
if (request.contains("http://")){
StringBuilder sb = new StringBuilder(request);
sb.delete(0,4);
sb.delete(sb.length()-9,sb.length());
makeConnection(sb.toString());
break;}
in.close();
}
}
private void makeConnection(String url) throws IOException{
//Establish connection between proxy & web server on socket
try {
InetAddress addr;
URL aURL = new URL(url);
System.out.println("URL IS " + aURL.toString());
Socket server = new Socket(urlString,80);
addr = server.getInetAddress();
System.out.println("IP is: " + addr);
System.out.println("Connected to " + addr);
server.close();
}
catch (IOException e) {
System.out.println("Can't connect");
System.out.println(e);
}
}
From your update, it seems like you are trying to create a socket connection to "http://www.hotmail.com". This should just be www.hotmail.com. The "http://" before this is a problem.