Hi.
This is my first post - welcome everybody!:)
My goal is to create a client sending messages and a server which echoes it back.
Here is Server.java code:
And Client.java code:Code:public class Server
{
ByteBuffer buffer = ByteBuffer.allocate(1024);
public Server(int port) throws IOException
{
startServer(port);
}
public void startServer(int port) throws IOException
{
Selector selector = Selector.open();
ServerSocketChannel ssc = ServerSocketChannel.open();
ssc.configureBlocking(false);
ServerSocket ss = ssc.socket();
InetSocketAddress address = new InetSocketAddress("localhost", port);
ss.bind(address);
ssc.register(selector, SelectionKey.OP_ACCEPT);
for(;;)
{
selector.select();
Set selectedKeys = selector.selectedKeys();
Iterator it = selectedKeys.iterator();
while(it.hasNext())
{
System.out.println("1. Something happens...");
SelectionKey key = (SelectionKey)it.next();
if(key.isAcceptable())
{
ServerSocketChannel ssc2 = (ServerSocketChannel)key.channel();
SocketChannel sc = ssc2.accept();
sc.configureBlocking(false);
SelectionKey newKey = sc.register(selector, SelectionKey.OP_READ);
it.remove();
System.out.println("2. Someone has connected...");
continue;
}
if(key.isReadable())
{
System.out.println("3. Ready for reading...");
SocketChannel sc = (SocketChannel)key.channel();
while(true)
{
buffer.clear();
int r = sc.read(buffer);
if(r <= 0)
break;
buffer.flip();
sc.write(buffer);
}
it.remove();
}
}
}
}
public static void main(String[] args)
{
try
{
new Server(9999);
} catch (IOException e)
{
System.out.println("Server exception: " + e.getMessage());
}
}
}
Code:public class Client
{
public Client(int port) throws IOException
{
SocketChannel socketChannel = SocketChannel.open();
socketChannel.configureBlocking(false);
socketChannel.connect(new InetSocketAddress("localhost", port));
try
{
Thread.sleep(3000);
} catch (InterruptedException e)
{
e.printStackTrace();
}
socketChannel.close();
}
public static void main(String[] args)
{
try
{
new Client(9999);
} catch (IOException e)
{
System.out.println("Client exception: " + e.getMessage());
}
}
}
My problems are following:
1. When client closes after 3 seconds, server permanently generates such messages:
(...)
1. Something happens...
3. Ready for reading...
(...)
How can I disconnect and display (on the server's side) only one message:
"Client has disconnected" and avoid repeating those above?
2. Could I have an example of sending message from client to server and vice versa? I've been trying to do this, but some exceptions are generated...
3. How can I send whole objects through channels (serialization)?
Thanks in advance for help!;)

