Wrong client and server UDP connection in Java - server

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 {
}

Related

netty SimpleChannelInboundHandler<String> channelRead0 only occasionally invoked

I know that there are several similar questions that have either been answered or still outstanding, however, for the life of me...
Later Edit 2016-08-25 10:05 CST - Actually, I asked the wrong question.
The question is the following: given that I have both a netty server (taken from DiscardServer example) and a netty client - (see above) what must I do to force the DiscardServer to immediately send the client a request?
I have added an OutboundHandler to the server and to the client.
After looking at both the DiscardServer and PingPongServer examples, there is an external event occurring to kick off all the action. In the case of Discard server, it is originally waiting for a telnet connection, then will transmit whatever was in the telnet msg to the client.
In the case of PingPongServer, the SERVER is waiting on the client to initiate action.
What I want is for the Server to immediately start transmitting after connection with the client. None of the examples from netty seem to do this.
If I have missed something, and someone can point it out, much good karma.
My client:
public final class P4Listener {
static final Logger LOG;
static final String HOST;
static final int PORT;
static final Boolean SSL = Boolean.FALSE;
public static Dto DTO;
static {
LOG = LoggerFactory.getLogger(P4Listener.class);
HOST = P4ListenerProperties.getP4ServerAddress();
PORT = Integer.valueOf(P4ListenerProperties.getListenerPort());
DTO = new Dto();
}
public static String getId() { return DTO.getId(); }
public static void main(String[] args) throws Exception {
final SslContext sslCtx;
if (SSL) {
LOG.info("{} creating SslContext", getId());
sslCtx = SslContextBuilder.forClient().trustManager(InsecureTrustManagerFactory.INSTANCE).build();
} else {
sslCtx = null;
}
EventLoopGroup group = new NioEventLoopGroup();
try {
Bootstrap b = new Bootstrap();
b.group(group).channel(NioSocketChannel.class)
.handler(new LoggingHandler(LogLevel.INFO))
.handler(new P4ListenerInitializer(sslCtx));
// Start the connection attempt.
LOG.debug(" {} starting connection attempt...", getId());
Channel ch = b.connect(HOST, PORT).sync().channel();
// ChannelFuture localWriteFuture = ch.writeAndFlush("ready\n");
// localWriteFuture.sync();
} finally {
group.shutdownGracefully();
}
}
}
public class P4ListenerHandler extends SimpleChannelInboundHandler<String> {
static final Logger LOG = LoggerFactory.getLogger(P4ListenerHandler.class);
static final DateTimeFormatter DTFormatter = DateTimeFormatter.ofPattern("yyyyMMdd-HHMMss.SSS");
static final String EndSOT;
static final String StartSOT;
static final String EOL = "\n";
static final ClassPathXmlApplicationContext AppContext;
static {
EndSOT = P4ListenerProperties.getEndSOT();
StartSOT = P4ListenerProperties.getStartSOT();
AppContext = new ClassPathXmlApplicationContext(new String[] { "applicationContext.xml" });
}
private final RequestValidator rv = new RequestValidator();
private JAXBContext jaxbContext = null;
private Unmarshaller jaxbUnmarshaller = null;
private boolean initialized = false;
private Dto dto;
public P4ListenerHandler() {
dto = new Dto();
}
public Dto getDto() { return dto; }
public String getId() { return getDto().getId(); }
Message convertXmlToMessage(String xml) {
if (xml == null)
throw new IllegalArgumentException("xml message is null!");
try {
jaxbContext = JAXBContext.newInstance(p4.model.xml.request.Message.class, p4.model.xml.request.Header.class,
p4.model.xml.request.Claims.class, p4.model.xml.request.Insurance.class,
p4.model.xml.request.Body.class, p4.model.xml.request.Prescriber.class,
p4.model.xml.request.PriorAuthorization.class,
p4.model.xml.request.PriorAuthorizationSupportingDocumentation.class);
jaxbUnmarshaller = jaxbContext.createUnmarshaller();
StringReader strReader = new StringReader(xml);
Message m = (Message) jaxbUnmarshaller.unmarshal(strReader);
return m;
} catch (JAXBException jaxbe) {
String error = StacktraceUtil.getCustomStackTrace(jaxbe);
LOG.error(error);
throw new P4XMLUnmarshalException("Problems when attempting to unmarshal transmission string: \n" + xml,
jaxbe);
}
}
#Override
public void channelActive(ChannelHandlerContext ctx) {
LOG.debug("{} let server know we are ready", getId());
ctx.writeAndFlush("Ready...\n");
}
/**
* Important - this method will be renamed to
* <code><b>messageReceived(ChannelHandlerContext, I)</b></code> in netty 5.0
*
* #param ctx
* #param msg
*/
#Override
protected void channelRead0(ChannelHandlerContext ctx, String msg) throws Exception {
ChannelFuture lastWriteFuture = null;
LOG.debug("{} -- received message: {}", getId(), msg);
Channel channel = ctx.channel();
Message m = null;
try {
if (msg instanceof String && msg.length() > 0) {
m = convertXmlToMessage(msg);
m.setMessageStr(msg);
dto.setRequestMsg(m);
LOG.info("{}: received TIMESTAMP: {}", dto.getId(), LocalDateTime.now().format(DTFormatter));
LOG.debug("{}: received from server: {}", dto.getId(), msg);
/*
* theoretically we have a complete P4(XML) request
*/
final List<RequestFieldError> errorList = rv.validateMessage(m);
if (!errorList.isEmpty()) {
for (RequestFieldError fe : errorList) {
lastWriteFuture = channel.writeAndFlush(fe.toString().concat(EOL));
}
}
/*
* Create DBHandler with message, messageStr, clientIp to get
* dbResponse
*/
InetSocketAddress socketAddress = (InetSocketAddress) channel.remoteAddress();
InetAddress inetaddress = socketAddress.getAddress();
String clientIp = inetaddress.getHostAddress();
/*
* I know - bad form to ask the ApplicationContext for the
* bean... BUT ...lack of time turns angels into demons
*/
final P4DbRequestHandler dbHandler = (P4DbRequestHandler) AppContext.getBean("dbRequestHandler");
// must set the requestDTO for the dbHandler!
dbHandler.setClientIp(clientIp);
dbHandler.setRequestDTO(dto);
//
// build database request and receive response (string)
String dbResponse = dbHandler.submitDbRequest();
/*
* create ResponseHandler and get back response string
*/
P4ResponseHandler responseHandler = new P4ResponseHandler(dto, dbHandler);
String responseStr = responseHandler.decodeDbServiceResponse(dbResponse);
/*
* write response string to output and repeat exercise
*/
LOG.debug("{} -- response to be written back to server:\n {}", dto.getId(), responseStr);
lastWriteFuture = channel.writeAndFlush(responseStr.concat(EOL));
//
LOG.info("{}: response sent TIMESTAMP: {}", dto.getId(), LocalDateTime.now().format(DTFormatter));
} else {
throw new P4EventException(dto.getId() + " -- Message received is not a String");
}
processWriteFutures(lastWriteFuture);
} catch (Throwable t) {
String tError = StacktraceUtil.getCustomStackTrace(t);
LOG.error(tError);
} finally {
if (lastWriteFuture != null) {
lastWriteFuture.sync();
}
}
}
private void processWriteFutures(ChannelFuture writeFuture) throws InterruptedException {
// Wait until all messages are flushed before closing the channel.
if (writeFuture != null) {
writeFuture.sync();
}
}
#Override
public void exceptionCaught(ChannelHandlerContext ctx, Throwable cause) {
cause.printStackTrace();
ctx.close();
}
}
/**
* Creates a newly configured {#link ChannelPipeline} for a new channel.
*/
public class P4ListenerInitializer extends ChannelInitializer<SocketChannel> {
private static final StringDecoder DECODER = new StringDecoder();
private static final StringEncoder ENCODER = new StringEncoder();
private final SslContext sslCtx;
public P4ListenerInitializer(SslContext sslCtx) {
this.sslCtx = sslCtx;
}
#Override
public void initChannel(SocketChannel ch) {
P4ListenerHandler lh = null;
ChannelPipeline pipeline = ch.pipeline();
if (sslCtx != null) {
P4Listener.LOG.info("{} -- constructing SslContext new handler ", P4Listener.getId());
pipeline.addLast(sslCtx.newHandler(ch.alloc(), P4Listener.HOST, P4Listener.PORT));
} else {
P4Listener.LOG.info("{} -- SslContext null; bypassing adding sslCtx.newHandler(ch.alloc(), P4Listener.HOST, P4Listener.PORT) ", P4Listener.getId());
}
// Add the text line codec combination first,
pipeline.addLast(new DelimiterBasedFrameDecoder(8192, Delimiters.lineDelimiter()));
pipeline.addLast(DECODER);
P4Listener.LOG.debug("{} -- added Decoder ", P4Listener.getId());
pipeline.addLast(ENCODER);
P4Listener.LOG.debug("{} -- added Encoder ", P4Listener.getId());
// and then business logic.
pipeline.addLast(lh = new P4ListenerHandler());
P4Listener.LOG.debug("{} -- added P4ListenerHandler: {} ", P4Listener.getId(), lh.getClass().getSimpleName());
}
}
#Sharable
public class P4ListenerOutboundHandler extends ChannelOutboundHandlerAdapter {
static final Logger LOG = LoggerFactory.getLogger(P4ListenerOutboundHandler.class);
private Dto outBoundDTO = new Dto();
public String getId() {return this.outBoundDTO.getId(); }
#Override
public void write(ChannelHandlerContext ctx, Object msg, ChannelPromise promise) {
try {
ChannelFuture lastWrite = ctx.write(Unpooled.copiedBuffer((String) msg, CharsetUtil.UTF_8));
try {
if (lastWrite != null) {
lastWrite.sync();
promise.setSuccess();
}
} catch (InterruptedException e) {
promise.setFailure(e);
e.printStackTrace();
}
} finally {
ReferenceCountUtil.release(msg);
}
}
}
output from client
Just override channelActive(...) on the handler of the server and trigger a write there.

eofexception on the server side of sslsocket while there is data for sure

I have this dummy program:
package com.company;
import javax.net.ssl.*;
import java.io.*;
import java.net.InetSocketAddress;
import java.net.ServerSocket;
import java.net.Socket;
import java.net.SocketTimeoutException;
import java.security.*;
import java.security.cert.CertificateException;
class MyClass implements Serializable
{
private int i,j;
public MyClass(int i, int j)
{
this.i = i;
this.j = j;
}
public int getJ()
{
return j;
}
public void setJ(int j)
{
this.j = j;
}
public int getI()
{
return i;
}
public void setI(int i)
{
this.i = i;
}
}
class SSLContextHelper
{
static SSLContext createSSLContext(String path) throws KeyStoreException, UnrecoverableKeyException, NoSuchAlgorithmException, IOException, KeyManagementException, CertificateException
{
KeyStore keyStore = KeyStore.getInstance("PKCS12");
keyStore.load(new FileInputStream(path),"DSL2137976".toCharArray());
// Create key manager
KeyManagerFactory keyManagerFactory = KeyManagerFactory.getInstance("SunX509");
keyManagerFactory.init(keyStore, "DSL2137976".toCharArray());
KeyManager[] km = keyManagerFactory.getKeyManagers();
// Create trust manager
TrustManagerFactory trustManagerFactory = TrustManagerFactory.getInstance("SunX509");
trustManagerFactory.init(keyStore);
TrustManager[] tm = trustManagerFactory.getTrustManagers();
// Initialize SSLContext
SSLContext sslContext = SSLContext.getInstance("TLSv1.2");
sslContext.init(km, tm, new SecureRandom());
return sslContext;
}
}
class ServerThread extends Thread
{
ServerSocket server;
Socket client;
ObjectOutputStream out;
ObjectInputStream in;
boolean issecure;
SSLContext sslContext;
public ServerThread(int port, boolean issecure) throws IOException, UnrecoverableKeyException, CertificateException, NoSuchAlgorithmException, KeyStoreException, KeyManagementException
{
this.issecure=issecure;
client=null;
if(issecure)
{
sslContext = SSLContextHelper.createSSLContext("/usr/lib/jvm/java-8-openjdk/jre/lib/security/ssltest");
SSLServerSocketFactory sslServerSocketFactory = sslContext.getServerSocketFactory();
server = sslServerSocketFactory.createServerSocket(port);
server.setSoTimeout(200);
}
else
server=new ServerSocket(port);
}
#Override
public void run()
{
while (true)
{
try
{
if(client==null)
{
if (issecure)
{
SSLSocket clientssl = (SSLSocket) server.accept();
clientssl.setEnabledCipherSuites(clientssl.getSupportedCipherSuites());
clientssl.startHandshake();
client = clientssl;
}
else
client = server.accept();
in = new ObjectInputStream(client.getInputStream());
out = new ObjectOutputStream(client.getOutputStream());
client.setSoTimeout(200);
}
String[] req = in.readUTF().split("\n");
out.writeUTF("hello I'm the server");
out.flush();
req = in.readUTF().split("\n");
out.writeUTF("I mean I'll serve you");
out.flush();
}
catch (IOException e)
{
e.printStackTrace();
}
}
}
}
public class Main
{
public static void main(String... args) throws IOException, ClassNotFoundException, UnrecoverableKeyException, CertificateException, NoSuchAlgorithmException, KeyStoreException, KeyManagementException
{
ServerThread serverThread=new ServerThread(14200, true);
serverThread.setDaemon(true);
serverThread.start();
ServerThread mail=new ServerThread(14201, false);
mail.setDaemon(true);
mail.start();
try
{
Thread.sleep(5000);
}
catch (InterruptedException e)
{
e.printStackTrace();
}
SSLSocket client=(SSLSocket)SSLContextHelper.createSSLContext("/usr/lib/jvm/java-8-openjdk/jre/lib/security/ssltest").getSocketFactory().createSocket();
client.connect(new InetSocketAddress("localhost",14200),5000);
Socket mailclient = new Socket();
mailclient.connect(new InetSocketAddress("localhost", 14201), 5000);
client.startHandshake();
client.setSoTimeout(5000);
ObjectOutputStream out = new ObjectOutputStream(client.getOutputStream());
ObjectInputStream in = new ObjectInputStream(client.getInputStream());
out.writeUTF("hello\nhow are you");
out.flush();
System.out.println(in.readUTF());
out.writeUTF("what\nI didn't understand");
out.flush();
System.out.println(in.readUTF());
int i=0;
while (i<=1)
{
try
{
try
{
Thread.sleep(10000);
}
catch (InterruptedException e)
{
e.printStackTrace();
}
out.writeUTF("hello\nhow are you");
out.flush();
System.out.println(in.readUTF());
out.writeUTF("what\nI didn't understand");
out.flush();
System.out.println(in.readUTF());
i++;
}
catch (SocketTimeoutException ignored)
{
}
}
}
}
It's just a simulation of a real program I have, the Thread.sleep on the client side is a simulation of a user doing some interaction with the system before clicking a button(the first sleep is the simulation of the user putting the sign in information, the second sleep is the user opening tab,clicking link,answers dialogs,etc).
Unfortunately I'm getting EOFException in the server side right after the server.accept succeed(that is when the client connects).
I know that this exception occurs when there is no data to get but this happens even after these two lines(the first ones before the while loop) on the client side:
out.writeUTF("hello\nhow are you");
out.flush();
after these two lines the client waits 5 seconds(the timeout I put) , during this 5 seconds the server keeps on its EOFException, when the timeout finishes the client gets SocketTimeoutException and the program exits.
The original program is getting the same EOFException on the server side, it began when I moved to SSLSockets.
So what's the issue here ?
Edit
I have found that when I remove the timeout(the Read timeout not the Accept timeout) it works perfectly.
Playing with the timeout, setting it to different value gives me strange NullPointerExceptions(that in is null !!!!!!!!!!).
I need the timeout because in my real program the server won't wait the client forever, it has other clients to serve as well .
Why timeout causes this ?

Sending message with external call in netty socket programming

I'm new to socket programming and Netty framework. I was trying to modify the Echo Server example so that the message is not sent from client as soon as a message is received, but a call from another thread would trigger the client send a message to the server.
The problem is, the server does not get the message unless the client sends it from readChannel or MessageReceived or channelActive which are where the server is specified with a parameter (ChannelHandlerContext). I couldn't manage to find a way to save the server channel and send a message later and repeatedly.
Here's my Client Handler code;
import io.netty.channel.ChannelHandlerAdapter;
import io.netty.channel.ChannelHandlerContext;
public class EchoClientHandler extends ChannelHandlerAdapter {
ChannelHandlerContext server;
#Override
public void channelActive(ChannelHandlerContext ctx) {
this.server = ctx;
}
#Override
public void channelRead(ChannelHandlerContext ctx, Object msg) throws Exception {
// ctx.write(msg); //not
}
#Override
public void channelReadComplete(ChannelHandlerContext ctx) throws Exception {
//ctx.flush();
}
public void externalcall(String msg) throws Exception {
if(server!=null){
server.writeAndFlush("[" + "] " + msg + '\n');
}
}
#Override
public void exceptionCaught(ChannelHandlerContext ctx, Throwable cause) {
// Close the connection when an exception is raised.
ctx.close();
}
}
When Client creates the handler, it also creates a thread with a "SourceGenerator" object which gets the handler as parameter so as to call the externalcall() method.
import io.netty.bootstrap.Bootstrap;
import io.netty.channel.ChannelFuture;
import io.netty.channel.ChannelInitializer;
import io.netty.channel.ChannelOption;
import io.netty.channel.EventLoopGroup;
import io.netty.channel.nio.NioEventLoopGroup;
import io.netty.channel.socket.SocketChannel;
import io.netty.channel.socket.nio.NioSocketChannel;
/**
* Sends one message when a connection is open and echoes back any received
* data to the server. Simply put, the echo client initiates the ping-pong
* traffic between the echo client and server by sending the first message to
* the server.
*/
public class EchoClient {
private final String host;
private final int port;
public EchoClient(String host, int port, int firstMessageSize) {
this.host = host;
this.port = port;
}
public void run() throws Exception {
// Configure the client.
EventLoopGroup group = new NioEventLoopGroup();
final EchoClientHandler x = new EchoClientHandler();
SourceGenerator sg = new SourceGenerator(x);
new Thread(sg).start();
try {
Bootstrap b = new Bootstrap();
b.group(group)
.channel(NioSocketChannel.class)
.option(ChannelOption.TCP_NODELAY, true)
.handler(new ChannelInitializer<SocketChannel>() {
#Override
public void initChannel(SocketChannel ch) throws Exception {
ch.pipeline().addLast(x);
}
});
// Start the client.
ChannelFuture f = b.connect(host, port).sync();
// Wait until the connection is closed.
f.channel().closeFuture().sync();
} finally {
// Shut down the event loop to terminate all threads.
group.shutdownGracefully();
}
}
public static void main(String[] args) throws Exception {
// Print usage if no argument is specified.
if (args.length < 2 || args.length > 3) {
System.err.println(
"Usage: " + EchoClient.class.getSimpleName() +
" <host> <port> [<first message size>]");
return;
}
// Parse options.
final String host = args[0];
final int port = Integer.parseInt(args[1]);
final int firstMessageSize;
if (args.length == 3) {
firstMessageSize = Integer.parseInt(args[2]);
} else {
firstMessageSize = 256;
}
new EchoClient(host, port, firstMessageSize).run();
}
}
and the SourceGenerator class;
public class SourceGenerator implements Runnable {
public String dat;
public EchoClientHandler asd;
public SourceGenerator(EchoClientHandler x) {
asd = x;
System.out.println("initialized source generator");
dat = "";
}
#Override
public void run() {
try{
while(true){
Thread.sleep(2000);
dat += "a";
asd.externalcall(dat);
System.out.print("ha!");
}
}catch(Exception e){
e.printStackTrace();
}
}
}
Thanks in advance!
If you want to write a String you need to have the StringEncoder in the ChannelPipeline.
Otherwise you can only send ByteBuf instances.

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!

Server and Java Applet: Connecting Socket

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.