Java - Enviar String por SocketChannel

 
Vista:
sin imagen de perfil

Enviar String por SocketChannel

Publicado por Mr. E (1 intervención) el 20/08/2015 05:59:30
Buenas:

Sucede que estoy haciendo un programa Cliente-Servidor con sockets de flujo no bloqueantes (ServerSocketChannel y SocketChannel) donde el cliente es un web browser, mi duda es: ¿Cómo envío texto plano o String a través de el ServerSocketChannel? según sé con el método socket.write() se envían ByteBuffer ¿Cómo hago para que el navegador lo interprete como texto? Aquí les dejo la parte de interés de mi código:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
package servidorhttp;
import java.io.*;
import java.net.*;
import java.nio.ByteBuffer;
import java.nio.CharBuffer;
import java.nio.channels.DatagramChannel;
import java.nio.channels.SelectionKey;
import java.nio.channels.Selector;
import java.nio.channels.ServerSocketChannel;
import java.nio.channels.SocketChannel;
import java.nio.charset.Charset;
import java.nio.charset.CharsetDecoder;
import java.nio.charset.CharsetEncoder;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.Paths;
import java.util.*;
/**
 *
 * @author eortega
 */
public class ServidorHTTP {
public static final int PUERTO = 5000;
public static ByteBuffer buffer = ByteBuffer.allocate(1024);
Charset charset = Charset.forName("UTF-8");
    /**
     * @param args the command line arguments
     * @throws java.io.IOException
     */
    public static void main(String[] args) throws IOException {
         Charset charset = Charset.forName("utf-8");
    CharsetEncoder encoder = charset.newEncoder();
    CharsetDecoder decoder = charset.newDecoder();
 
        try(Selector selector = Selector.open();
                ServerSocketChannel server = ServerSocketChannel.open()){
        if(selector.isOpen() && server.isOpen()){
            //configuración del socket
            server.configureBlocking(false);
            server.setOption(StandardSocketOptions.SO_RCVBUF, 256 * 1024);
            server.setOption(StandardSocketOptions.SO_REUSEADDR, true);
            server.bind(new InetSocketAddress(PUERTO));
            server.register(selector, SelectionKey.OP_ACCEPT);
            //configuración del socket
 
            System.out.println("Servidor conectado, esperando peticiones\n");
 
 
            while(true){
                selector.selectNow();
                Iterator keys = selector.selectedKeys().iterator();
                while(keys.hasNext()){
                    SelectionKey key = (SelectionKey) keys.next();
                    keys.remove();
                    if(key.isAcceptable()){
                        System.out.println("es aceptable");
                        ServerSocketChannel serverChannel = (ServerSocketChannel) key.channel();
                        SocketChannel cliente = serverChannel.accept();
                        cliente.configureBlocking(false);
                        System.out.println("Incoming connection from: " + cliente.getRemoteAddress());
                        //write a welcome message
                        cliente.write(ByteBuffer.wrap("Hello!\n".getBytes("UTF-8")));
                        cliente.register(selector, SelectionKey.OP_READ);
                        }
 
                    /* verificamos si el cliente ha escrito información en el canal*/
                    else if(key.isReadable()){
                        System.out.println("es readable");
                        SocketChannel cliente = (SocketChannel) key.channel();
                        buffer.clear();
                        int numRecv = cliente.read(buffer);
                        byte[] data = new byte[numRecv];
                        System.arraycopy(buffer.array(), 0, data, 0, numRecv);
                        String request = (new String(data, charset));
                        System.out.println("peticion" + request + "peticion");
                        /*if("".equals(request)){
                            String response = ("<html><head><title>Servidor WEB" + "</title><body bgcolor=\"#AACCFF\"<br>Linea Vacia</br>" 
                                    + "</body></html>");
                        cliente.write(encoder.encode(CharBuffer.wrap(response)));
                        }*/
 
                        /* obtener nombre de archivo */
                        int i;
				int f;
				if(request.toUpperCase().startsWith("GET"))
				{
					i=request.indexOf("/");
					f=request.indexOf(" ",i);
                            String FileName = request.substring(i+1,f);
                            System.out.println("nobre de archivo: " + FileName);
				}
 
                    }


Gracias de antemano.
Valora esta pregunta
Me gusta: Está pregunta es útil y esta claraNo me gusta: Está pregunta no esta clara o no es útil
0
Responder