Server and Java Applet: Connecting Socket - sockets

I have a java applet recently stopped working after the server is updated, more specifically:
1. The server is updated from Sun, running Solaris 9, 32 bit. (installed in 2005) to CentOS 5, (linux) on 64 bit.
2. The applet has two major classes 1) collect.class: collects data from a canvas 2) server.class: listens to collect.class through a PORT and acts accordingly;
but the applet got stuck and I check the start_server.sh (which produces a report nohup.out) there is a line
Exception creating server socket: java.net.BindException: Address already in use
This is weird, because PORT = 9999 which collect.class uses with no problem. How comes the problem happens only in server.class (who listens to collet.class).
Please help!
ADDITIONAL INFORMATION:
I.IN COLLECT.JAVA:
There is a canvas with grid on it, the user draw some area on the grid and click "Submit".
-> The MineCanvas.submit() is triggered -> The value of the area is computed by MineCanvas.ComputeGridValue() -> then Collect.cleintSend (stuck here)
import java.applet.*;
import java.awt.*;
import java.net.*;
import java.io.*;
import java.util.*;
public class Collect extends Applet {
...
public static final int PORT = 8888;
...
public boolean action(Event e, Object arg) {
...
if (arg.equals("Submit")) {
if (action(null, "Update Grid")) {
minecanvas.Submit();
} else {
return true;
}
}
return true;
}
...
public void clientSend(){
s = new Socket(this.getCodeBase().getHost(), PORT);
in = new DataInputStream(s.getInputStream());}
out = new DataOutputStream(s.getOutputStream());
listener = new SolutionListener(in, minecanvas);}
minecanvas.mode = MineCanvas.SUBMITTING;
minecanvas.repaint();
int n = 1;
out.writeBytes(minecanvas.gridh + "\n" + minecanvas.gridw + "\n");
for (int h = 0; h < minecanvas.gridh; h++) {
for (int w = 0; w < minecanvas.gridw; w++) {
out.writeBytes(n + " " + minecanvas.AllCells[w][h].net + "\n");
n++;
}
}
out.writeBytes("done\n");
s = null;
in = null;
out = null;
}
}
class MineCanvas extends Canvas {
...
public int gridw = 0; // number of grid squares width-ly
public int gridh = 0; // number of grid squares height-ly
public GridCell[][] AllCells; // array of grid cells comprising the grid
...
// compute values for minecanvas
public void ComputeGridValue() {...}
public void Submit() {
ComputeGridValue();
parent.clientSend();
}
...
}
...
}
II. SERVER.JAVA
import java.io.*;
import java.net.*;
public class Server extends Thread {
private OPM_Server opm; // this is the corresponding server for collect
...
public Server() {
...
opm = new OPM_Server();
}
public static void main(String[] args) {
new Server();
}
}
...
// OPM: correspond to Collect
class OPM_Server extends Thread {
public final static int DEFAULT_PORT = 8888;
protected int port;
protected ServerSocket listen_socket;
public static void fail(Exception e, String msg) {
System.err.println(msg + ": " + e);
System.exit(1);
}
public OPM_Server() {
this.port = DEFAULT_PORT;
try { listen_socket = new ServerSocket(port); }
catch (IOException e){ fail(e, "Exception creating server socket");}
System.out.println("Server: listening on port " + port);
this.start();
}
public void run() {
try {
while(true) {
System.out.println("I got to before ServerSocket");
Socket client_socket = listen_socket.accept();
OPM_Connection c = new OPM_Connection(client_socket);
}
}
catch (IOException e) {fail(e, "Exception while listening for connections");}
}
}
...
class OPM_Connection extends Thread {
protected Socket client;
protected BufferedReader in;
protected DataOutputStream out;
File mine_data = new File("mine_data"); // output file data
FileOutputStream file_stream;
DataOutputStream file_out;
public OPM_Connection(Socket client_socket) {
client = client_socket;
try {
in = new BufferedReader(new InputStreamReader(client.getInputStream()));
out = new DataOutputStream(client.getOutputStream());
} catch (IOException e) {
try {
client.close();
} catch (IOException e2) {
}
;
System.err.println("Exception while getting socket stream: "
+ e.toString());
return;
}
this.start();
}
public void run() {
...
file_stream = new FileOutputStream(mine_data);
file_out = new DataOutputStream(file_stream);
...// write to mine data
file_out = null;
if (inputGood == true) {
System.out.println(pid + "> ---Got all info from client");
Runtime r = Runtime.getRuntime();
Process Aproc = null;
Process Bproc = null;
int returnVal = -1;
try {
Aproc = r.exec("runOPM");
} catch (IOException e) {
inputGood = false;
System.out.println(pid + "> runOPM didn't exec");
}
try {
returnVal = Aproc.waitFor();
} catch (InterruptedException e) {
inputGood = false;
System.out.println(pid + "> runOPM didn't return");
}
System.out.println(pid + "> ---All execing done");
File report = new File("mine_report");
FileInputStream report_stream = null;
...
// create a mine report
System.out.println(pid + "> ---Done sending data back to client");
}
try {
client.close();
} catch (IOException e2) {
}
;
System.out.println(pid + "> EXITING THREAD");
}
}

Exception creating server socket: java.net.BindException: Address
already in use
This exception means that the port number the socket is trying to bind to (the port number your socket is trying to use in the local-end of the connection) is already in use by some other program. To fix it, you either need to find out what other software is using the port and see if you can safely change it, or change the port your program is using.
Edit: It might be worth trying to look for rarely used port(s), to lessen the chance of using yet another port that is known to be used by some common software, here's Wikipedias list of typical TCP and UDP ports in use by common programs and services.

Related

Wrong client and server UDP connection in Java

I must to do chat server for my subject.
Where is my problem ?
I need to write UDP server class which should send and receive messages from users and transfer it to GUI
Second server should have methods for collect public keys of any user, changing owns ect. Additionally he should store this these keys
What do I have?
I have some code from first server, two Threads for sending and receiving messages and some code in client , but it isn't synchronized. And I don't know how to do it
This is some code from client main method: tfServer --> text field for getting this from user
InetAddress ia = InetAddress.getByName(tfServer.getText());
SenderThread sender = new SenderThread(ia,Integer.valueOf(tfPort.getText()));
sender.start();
ReceiverThread receiver = new ReceiverThread(sender.getSocket());
receiver.start();
First server code :
import java.net.* ;
public class Server {
int port;
private final static int PACKETSIZE = 100 ;
private boolean isStopped = false;
public Server(){
}
public Server(int port) {
this.port = port;
}
public void stop() {
this.isStopped = true;
}
public void start() {
try
{
DatagramSocket socket = new DatagramSocket(this.port) ;
System.out.println( "Serwer gotowy..." ) ;
if(!this.isStopped){
for( ;; ){
DatagramPacket packet = new DatagramPacket( new byte[PACKETSIZE], PACKETSIZE ) ;
socket.receive( packet ) ;
System.out.println( packet.getAddress() + " " + packet.getPort() + ": " + new String(packet.getData()) ) ;
socket.send( packet ) ;
}
}
}
catch( Exception e )
{
System.out.println( e ) ;
}
}
}
And class from first server to receive :
import java.io.IOException;
import java.net.DatagramPacket;
import java.net.DatagramSocket;
import java.net.SocketException;
public class ReceiverThread extends Thread {
private DatagramSocket udpClientSocket;
private boolean stopped = false;
public ReceiverThread(DatagramSocket ds) throws SocketException {
this.udpClientSocket = ds;
}
public void halt() {
this.stopped = true;
}
public void run() {
byte[] receiveData = new byte[1024];
while (true) {
if (stopped)
return;
DatagramPacket receivePacket = new DatagramPacket(receiveData, receiveData.length);
try {
udpClientSocket.receive(receivePacket);
String serverReply = new String(receivePacket.getData(), 0, receivePacket.getLength());
System.out.println("UDPClient: Response from Server: \"" + serverReply + "\"\n");
Thread.yield();
}
catch (IOException ex) {
System.err.println(ex);
}
}
}
}
Second class from first server to send messages :
import java.io.IOException;
import java.net.DatagramPacket;
import java.net.DatagramSocket;
import java.net.SocketException;
public class ReceiverThread extends Thread {
private DatagramSocket udpClientSocket;
private boolean stopped = false;
public ReceiverThread(DatagramSocket ds) throws SocketException {
this.udpClientSocket = ds;
}
public void halt() {
this.stopped = true;
}
public void run() {
byte[] receiveData = new byte[1024];
while (true) {
if (stopped)
return;
DatagramPacket receivePacket = new DatagramPacket(receiveData, receiveData.length);
try {
udpClientSocket.receive(receivePacket);
String serverReply = new String(receivePacket.getData(), 0, receivePacket.getLength());
System.out.println("UDPClient: Response from Server: \"" + serverReply + "\"\n");
Thread.yield();
}
catch (IOException ex) {
System.err.println(ex);
}
}
}
}
And server PKI :
public class ServerPKI {
}

Java Socket ArrayList NullPointer Exception

Whenever I run my Chat Server it works until the client connects and then I get a Null Pointer exception at
connections.add(socket);
which crashes it and then this happens every time I run it.
I know my client side is fine because I watched a tutorial a few months ago on how to do this and that server works with my client without crashing
private static ServerSocket server;
private static Socket socket;
private static Scanner input;
private static PrintWriter output;
private static final int port = 444;
private static String message;
private static ArrayList<Socket> connections;
private static Server serverClass;
public Server() {
message = "";
connections = new ArrayList<Socket>();
serverClass = new Server();
}
public void run() {
try {
try {
input = new Scanner(socket.getInputStream());
output = new PrintWriter(socket.getOutputStream());
while(true) {
checkConnection();
if(!input.hasNext()) {
return;
}
message = input.nextLine();
System.out.println("Client said: " + message);
for(int i = 1; i <= connections.size(); i++) {
Socket tempSock = (Socket) connections.get(i - 1);
output.println(message);
output.flush();
}
}
}
finally {
socket.close();
}
}
catch(Exception e) {
System.out.print(e);
}
}
public void checkConnection() throws IOException {
if(!socket.isConnected()) {
for(int i = 1; i <= connections.size(); i++) {
if(connections.get(i) == socket) {
connections.remove(i);
}
}
for(int i = 1; i <= connections.size(); i++) {
Socket disconnectedUser = (Socket) connections.get(i - 1);
System.out.println(disconnectedUser + " has Disconnected!");
}
}
}
public static void main(String[] args) throws IOException{
try {
server = new ServerSocket(port);
System.out.println("Waiting for Clients... ");
while(true) {
socket = server.accept();
connections.add(socket);
System.out.println("Client connected from: " + socket.getLocalAddress().getHostName());
Thread thread = new Thread(serverClass);
thread.start();
}
}
catch(Exception e) {
e.printStackTrace();
}
}
If you get an NPE at connections.add(socket), it can only be because connections is null. Which it is, because you haven't constructed an instance of Server: instead you are trying to execute all its code from main(). The only place you call new Server() from is inside the constructor for Server, which you have clearly never executed at all, as you would have got a StackOverflowError from the infinite recursion.
This code is a real mess:
fix the infinite recursion
construct an instance of Server in your main() method
make connections non-static
make socket a local variable in the accept loop
fix your loops to iterate from 0 to connections.size()-1
and try again.

How can I test, whether my deployed background server application on AWS beanstalk gets messages through a socketstream with an android mobile client?

The overall topic is actually like a Chat Application sending a simple string message to an aws server, which uses the message to make calculations server-side and sending a simple string message as a solution back to the client.
Server: I have written a Server Class and deployed it through eclipse to aws beanstalk. (see code Server)
Client: My android device creates a socket, establishes a successful connection to my aws beanstalk ip and 8080 port, while iterating through an endless while loop in a thread listening to incoming messages from the server. (see code Client and ClientThread)
Problem: My problem is that I don't know how to check whether the server receives the connection request and messages from the client. How do I make sure, that code on aws beanstalk actually runs in background continuously listening for incoming connections? I have deployed the code, does aws beanstalk automatically start the main method of the Server Class and runs it infinitely?
Here's the server code:
import java.io.BufferedInputStream;
import java.io.BufferedOutputStream;
import java.io.DataInputStream;
import java.io.DataOutputStream;
import java.io.IOException;
import java.net.ServerSocket;
import java.net.Socket;
public class Server {
public static void main(String args[]) {
ServerSocket server = null;
System.out.println("Trying to open serversocket!");
try {
server = new ServerSocket(8080);
} catch (IOException e) {
System.out.println("Error on port: 8080 " + ", " + e);
System.exit(1);
}
System.out
.println("Server setup and waiting for client connection ...");
Socket client = null;
try {
client = server.accept();
} catch (IOException e) {
System.out.println("Did not accept connection: " + e);
System.exit(1);
}
System.out
.println("Client connection accepted. Moving to local port ...");
try {
DataInputStream streamIn = new DataInputStream(
new BufferedInputStream(client.getInputStream()));
DataOutputStream streamOut = new DataOutputStream(
new BufferedOutputStream(client.getOutputStream()));
boolean done = false;
String line;
int i = 4;
while (!done) {
line = streamIn.readUTF();
if (line.equalsIgnoreCase(".bye"))
done = true;
else
System.out.println("Client says: " + line);
if (i == 4) {
streamOut
.writeUTF("Actually connected to Server with round "
+ i);
streamOut.flush();
i++;
}
}
streamIn.close();
streamOut.close();
client.close();
server.close();
} catch (IOException e) {
System.out.println("IO Error in streams " + e);
}
}
}
Here's the client code:
package com.amazon.aws.singlesensor;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.io.PrintWriter;
import java.net.Socket;
import java.net.UnknownHostException;
import android.util.Log;
class Client implements Runnable {
private Socket socket = null;
private InputStream streamIn = null;
private OutputStream streamOut = null;
public InputStream getStreamIn() {
return streamIn;
}
public Client(String serverName, int serverPort) {
System.out.println("Establishing connection. Please wait ...");
try {
socket = new Socket(serverName, serverPort);
Log.d("DEBUG", "Connected: " + socket);
start();
} catch (UnknownHostException uhe) {
Log.d("DEBUG", "Host unknown: " + uhe.getMessage());
} catch (IOException ioe) {
Log.d("DEBUG", "Unexpected exception: " + ioe.getMessage());
}
}
public void start() throws IOException {
streamIn = socket.getInputStream();
streamOut = socket.getOutputStream();
}
public void run() {
try {
streamOut.write(streamIn.read());
streamOut.flush();
} catch (IOException ioe) {
System.out.println("Sending error: " + ioe.getMessage());
stop();
}
}
public void handle(String msg) {
if (msg.equals(".bye")) {
System.out.println("Good bye. Press RETURN to exit ...");
stop();
} else
System.out.println(msg);
}
public void stop() {
try {
if (streamIn != null)
streamIn.close();
if (streamOut != null)
streamOut.close();
if (socket != null)
socket.close();
} catch (IOException ioe) {
System.out.println("Error closing ...");
}
}
public void send(String msg) {
PrintWriter printwriter = new PrintWriter(streamOut);
printwriter.write(msg);
printwriter.flush();
}
}
Here's the ClientThread Code
package com.amazon.aws.singlesensor;
import java.io.IOException;
import java.io.InputStream;
import android.os.Handler;
public class ClientThread extends Thread {
private Client client;
private InputStream input;
private String output;
private Handler handler;
private Runnable runner;
public ClientThread() {
}
public ClientThread(Client client, Handler handler, Runnable runner) {
this.setClient(client);
this.input = client.getStreamIn();
this.handler = handler;
this.runner = runner;
this.output = "";
}
public void run() {
int status = 0;
while (status != -1) {
try {
status = input.read();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
while (status != '~'){
try {
status = input.read();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
output = output + String.valueOf((char) status);
handler.post(runner);
}
output = output + "\n";
}
}
public String giveString(){
return output;
}
public void setClient(Client client) {
this.client = client;
}
public Client getClient() {
return client;
}
}
Thank you for your time!

Reading coils using JAMOD

I have written the following program to understand how to use JAMOD to access coils. Unfortunately it is throwing the error -
java.lang.IndexOutOfBoundsException
at java.io.BufferedInputStream.read(Unknown Source)
at java.io.DataInputStream.read(Unknown Source)
at net.wimpi.modbus.io.ModbusTCPTransport.readResponse(ModbusTCPTransport.java:177)
at net.wimpi.modbus.io.ModbusTCPTransaction.execute(ModbusTCPTransaction.java:193)
at TempReader.main(TempReader.java:27)
. x2 more times
.
java.io.EOFException
at java.io.DataInputStream.readUnsignedByte(Unknown Source)
at net.wimpi.modbus.io.BytesInputStream.readUnsignedByte(BytesInputStream.java:153)
at net.wimpi.modbus.io.ModbusTCPTransport.readResponse(ModbusTCPTransport.java:182)
at net.wimpi.modbus.io.ModbusTCPTransaction.execute(ModbusTCPTransaction.java:193)
at TempReader.main(TempReader.java:30)
net.wimpi.modbus.ModbusIOException: Executing transaction failed (tried 3 times)
at net.wimpi.modbus.io.ModbusTCPTransaction.execute(ModbusTCPTransaction.java:197)
at TempReader.main(TempReader.java:30)
In the program line 27 is "trans.execute()". The coil address I am trying to read is 0x7D1 (2001) or channel 0 Data type is 2 word. -
import java.net.*;
import java.io.*;
import net.wimpi.modbus.*;
import net.wimpi.modbus.msg.*;
import net.wimpi.modbus.io.*;
import net.wimpi.modbus.net.*;
import net.wimpi.modbus.util.*;
public class TempReader {
public static void main(String Args[]){
TCPMasterConnection con = null;
ModbusTCPTransaction trans = null;
ReadCoilsRequest rcreq=null;
ReadCoilsResponse rcres=null;
InetAddress addr = null;
int port = Modbus.DEFAULT_PORT;
byte byteArray[]={(byte)192, (byte)168, (byte)0, (byte)182};
try {
addr=InetAddress.getByAddress(byteArray);
con=new TCPMasterConnection(addr);
con.setPort(502);
con.connect();
rcreq=new ReadCoilsRequest(2001, 1);
trans=new ModbusTCPTransaction(con);
trans.setRequest(rcreq);
trans.execute();
rcres=(ReadCoilsResponse)trans.getResponse();
System.out.println("Response : "+rcres.getCoils().toString());
con.close();
}
catch(Exception e){
con.close();
e.printStackTrace();
}
}
}
The error of course repeats 3 times as set in ModbusTCPTransport class (I checked the class source) i.e 3 attempts before exit and program exits.
Where am I going wrong?
My sample Modbus TCP ReadMultipleRegistersRequest.
public static void main(String[] args) {
try {
/**************************************/
//Read And Write Register Sample
int port = Modbus.DEFAULT_PORT;
String refe = "4000";//HEX Address
int ref=Integer.parseInt(refe,16);//Hex to int
int count = 98; //the number Address to read
int SlaveAddr=1;
String astr = "192.168.1.202"; //Modbus Device
InetAddress addr = InetAddress.getByName(astr);
TCPMasterConnection con = new TCPMasterConnection(addr); //the connection
ModbusTCPTransaction trans = null; //the transaction
//1.Prepare the request
/************************************/
ReadMultipleRegistersRequest Rreq = new ReadMultipleRegistersRequest(ref,count);
ReadMultipleRegistersResponse Rres = new ReadMultipleRegistersResponse();
Rreq.setUnitID(SlaveAddr); //set Slave Address
Rres.setUnitID(SlaveAddr); //set Slave Address
//2. Open the connection
con.setPort(port);
con.connect();
con.setTimeout(2500);
//3. Start Transaction
trans = new ModbusTCPTransaction(con);
trans.setRetries(5);
trans.setReconnecting(true);
trans.setRequest(Rreq);
trans.execute();
/*Print Response*/
Rres = (ReadMultipleRegistersResponse) trans.getResponse();
System.out.println("Connected to= "+ astr + con.isConnected() + " / Start Register " + Integer.toHexString(ref));
count=1;
for (int k=0;k<count;k++){
System.out.println("The value READ: " + Rres.getRegisterValue(k));
}
/****************Close Connection**************/
con.close();
System.out.println("\nConnected = " + con.isConnected());
System.exit(0);//edit Java bug error
} catch (Exception ex) {
ex.printStackTrace();
}
}//main
If you want to make slave try this example:
import net.wimpi.modbus.net.*;
import net.wimpi.modbus.procimg.*;
import net.wimpi.modbus.ModbusCoupler;
public class TCPSlaveTest {
public static void main(String[] args) {
try {
/* The important instances and variables */
ModbusTCPListener listener = null;
SimpleProcessImage spi = null;
int port = Modbus.DEFAULT_PORT;
//1. Set port number from commandline parameter
if(args != null && args.length ==1) {
port = Integer.parseInt(args[0]);
}
//2. Prepare a process image
spi = new SimpleProcessImage();
spi.addDigitalOut(new SimpleDigitalOut(true));
spi.addDigitalOut(new SimpleDigitalOut(false));
spi.addDigitalIn(new SimpleDigitalIn(false));
spi.addDigitalIn(new SimpleDigitalIn(true));
spi.addDigitalIn(new SimpleDigitalIn(false));
spi.addDigitalIn(new SimpleDigitalIn(true));
spi.addRegister(new SimpleRegister(251));
spi.addInputRegister(new SimpleInputRegister(45));
//3. Set the image on the coupler
ModbusCoupler.getReference().setProcessImage(spi);
ModbusCoupler.getReference().setMaster(false);
ModbusCoupler.getReference().setUnitID(15);
//4. Create a listener with 3 threads in pool
listener = new ModbusTCPListener(3);
listener.setPort(port);
listener.start();
} catch (Exception ex) {
ex.printStackTrace();
}
}//main
}//class TCPSlaveTest

How do i accept multiple clients on this program?

Through a lot of learning and research, i wrote a server side program. But the problem with this program is that it doesn't accept multiple clients, and i also wanted to know how to send the output back to client side instead of displaying it on the server side. Can someone please help me out with the code? This is what I've tried till now -
class Program
{
private static Regex _regex = new Regex("not|http|console|application", RegexOptions.Compiled | RegexOptions.IgnoreCase | RegexOptions.CultureInvariant);
static void Main(string[] args)
{
{
TcpListener serversocket = new TcpListener(8888);
TcpClient clientsocket = default(TcpClient);
serversocket.Start();
Console.WriteLine(">> Server Started");
clientsocket = serversocket.AcceptTcpClient();
Console.WriteLine("Accept Connection From Client");
try
{
using (var reader = new StreamReader(clientsocket.GetStream()))
{
string line;
int lineNumber = 0;
while (null != (line = reader.ReadLine()))
{
lineNumber += 1;
foreach (Match match in _regex.Matches(line))
{
Console.WriteLine("Line {0} matches {1}", lineNumber, match.Value);
}
}
}
}
catch (Exception ex)
{
Console.Error.WriteLine(ex.ToString());
}
clientsocket.Close();
serversocket.Stop();
Console.WriteLine(" >> exit");
Console.ReadLine();
}
}
}
You could change it to something like this.
static void Main(string[] args)
{
TcpListener serversocket = new TcpListener(8888);
TcpClient clientsocket = default(TcpClient);
serversocket.Start();
Console.WriteLine(">> Server Started");
while(true)
{
clientsocket = serversocket.AcceptTcpClient();
Console.WriteLine("Accept Connection From Client");
LineMatcher lm = new LineMatcher(clientsocket);
Thread thread = new Thread(new ThreadStart(lm.Run));
thread.Start();
Console.WriteLine("Client connected");
}
serversocket.Stop();
Console.WriteLine(" >> exit");
Console.ReadLine();
}
And then have this seperate class handling the linematching
public class LineMatcher{
private static Regex _regex = new Regex("not|http|console|application", RegexOptions.Compiled | RegexOptions.IgnoreCase | RegexOptions.CultureInvariant);
private TcpClient _client;
public LineMatcher(TcpClient client)
{
_client = client;
}
public void Run()
{
try
{
using (var reader = new StreamReader(_client.GetStream()))
{
string line;
int lineNumber = 0;
while (null != (line = reader.ReadLine()))
{
lineNumber += 1;
foreach (Match match in _regex.Matches(line))
{
Console.WriteLine("Line {0} matches {1}", lineNumber, match.Value);
}
}
}
}
catch (Exception ex)
{
Console.Error.WriteLine(ex.ToString());
}
Console.WriteLine("Closing client");
_client.Close();
}
}
This is purely a proof of concept and is no way stable code ;)
Please note that this doesn't manage the child-threads in any way.
There is also no correct way of shutting down the listener because of the while(true)