2015-10-22 20:02:55 +02:00
|
|
|
package com.jenkov.nioserver.example;
|
|
|
|
|
|
|
|
import java.io.IOException;
|
2019-12-28 10:43:48 +01:00
|
|
|
|
|
|
|
import com.jenkov.nioserver.IMessageProcessor;
|
|
|
|
import com.jenkov.nioserver.Message;
|
|
|
|
import com.jenkov.nioserver.Server;
|
|
|
|
import com.jenkov.nioserver.http.HttpMessageReaderFactory;
|
2015-10-22 20:02:55 +02:00
|
|
|
|
|
|
|
/**
|
2019-12-28 10:43:48 +01:00
|
|
|
* Project: <strong>java-nio-server</strong><br>
|
|
|
|
* File: <strong>Main.java</strong><br>
|
|
|
|
* Created: <strong>19 Oct 2015</strong><br>
|
|
|
|
*
|
|
|
|
* @author jjenkov
|
2015-10-22 20:02:55 +02:00
|
|
|
*/
|
|
|
|
public class Main {
|
|
|
|
|
2019-12-28 10:43:48 +01:00
|
|
|
public static void main(String[] args) throws IOException {
|
2015-10-22 20:02:55 +02:00
|
|
|
|
2019-12-28 10:43:48 +01:00
|
|
|
String httpResponse = "HTTP/1.1 200 OK\r\n" + "Content-Length: 38\r\n" + "Content-Type: text/html\r\n" + "\r\n"
|
|
|
|
+ "<html><body>Hello World!</body></html>";
|
2015-10-22 20:02:55 +02:00
|
|
|
|
2019-12-28 10:43:48 +01:00
|
|
|
byte[] httpResponseBytes = httpResponse.getBytes("UTF-8");
|
2015-10-22 20:02:55 +02:00
|
|
|
|
2019-12-28 10:43:48 +01:00
|
|
|
IMessageProcessor messageProcessor = (request, writeProxy) -> {
|
|
|
|
System.out.println("Message Received from socket: " + request.socketId);
|
2015-10-24 14:48:03 +02:00
|
|
|
|
2019-12-28 10:43:48 +01:00
|
|
|
Message response = writeProxy.getMessage();
|
|
|
|
response.socketId = request.socketId;
|
|
|
|
response.writeToMessage(httpResponseBytes);
|
2015-10-24 14:48:03 +02:00
|
|
|
|
2019-12-28 10:43:48 +01:00
|
|
|
writeProxy.enqueue(response);
|
|
|
|
};
|
2015-10-22 20:02:55 +02:00
|
|
|
|
2019-12-28 10:43:48 +01:00
|
|
|
Server server = new Server(9999, new HttpMessageReaderFactory(), messageProcessor);
|
2015-10-22 20:02:55 +02:00
|
|
|
|
2019-12-28 10:43:48 +01:00
|
|
|
server.start();
|
|
|
|
}
|
|
|
|
}
|