> Try this here, and look at the Examples:
>
> http://java.sun.com/j2se/1.4.2/docs/guide/nio/index.html
import java.net.*;
import java.nio.*;
import java.nio.channels.*;
import java.nio.charset.*;
public class Server {
/** sempre da assisini */
public static void main(String[] args) throws Throwable {
ServerSocket server = new ServerSocket(9999);
Socket client = server.accept();
ReadableByteChannel channel =
Channels.newChannel(client.getInputStream());
ByteBuffer len = ByteBuffer.allocate(4); //4 byte = 1 int
channel.read(len);
len.flip();
ByteBuffer message =
ByteBuffer.allocateDirect(len.asIntBuffer().
while(message.hasRemaining()) {
channel.read(message);
}
message.flip();
Charset ch = Charset.forName("ISO-8859-1");
channel.close();
server.close();
}
}
package client;
import java.io.BufferedOutputStream;
import java.io.ByteArrayOutputStream;
import java.io.DataOutputStream;
import java.io.FileInputStream;
import java.io.OutputStreamWriter;
import java.net.*;
import java.nio.*;
import java.nio.channels.*;
import java.nio.charset.*;
public class Client {
public static void main(String[] args) throws Throwable {
Socket socket = new Socket("localhost", 9999);
DataOutputStream os = new
DataOutputStream(socket.getOutputStream());
String messaggio = "ciao";
os.writeBytes(messaggio);
os.flush();
os.close();
socket.close();
}
}
Exception:
Exception in thread "main" java.nio.BufferUnderflowException
at java.nio.Buffer.nextGetIndex(Unknown Source)
at java.nio.ByteBufferAsIntBufferB.get(Unknown Source)
at server.Server.main(Server.java:26)
I look the examples at the java guide but there isn't an example that
explain like a client io can send a msg to server NIO.
Lew - 06 Feb 2007 06:36 GMT
> I look the examples at the java guide but there isn't an example that
> explain like a client io can send a msg to server NIO.
The client can use different I/O libraries than the server. The client doesn't
even have to be written in the same language as the server. It simply has to
send and receive the right byte seuqences as expected at the other end.
- Lew