java 实现 websocket_怎样用java web和websocket实现网页即时通讯

展开全部

下面是一个java的多线程的WebServer的例子:

//import java.io.*;

import java.net.*;

//import java.util.*;

public final class WebServer {

public static void main(String argv[]) throws Exception

{

int port = 80;

// Establish the listen socket.

ServerSocket WebSocket = new ServerSocket(port);

while (true) {

// Listen for a TCP connection request.

Socket connectionSocket = WebSocket.accept();

//Construct object to process HTTP request message

HttpRequest request = new HttpRequest(connectionSocket);

Thread thread = new Thread(request); //Create new thread to process

thread.start(); //Start the thread

}

}

}

import java.io.*;

import java.net.*;

import java.util.*;

public final class HttpRequest implements Runnable {

final static String CRLF = "\r\n";//For convenience

Socket socket;

// Constructor

public HttpRequest(Socket socket) throws Exception

{

this.socket = socket;

}

// Implement the run() method of the Runnable interface.

public void run()

{

try {

processRequest();

} catch (Exception e) {

System.out.println(e);

}

}

private void processRequest() throws Exception

{

InputStream is = socket.getInputStream(); //Starts the input from client machine

DataOutputStream os = new DataOutputStream(

socket.getOutputStream());

// Set up input stream filters.

BufferedReader br = new BufferedReader(

new InputStreamReader(is));

String requestLine = br.readLine();

System.out.println(); //Echoes request line out to screen

System.out.println(requestLine);

//The following obtains the IP address of the incoming connection.

InetAddress incomingAddress = socket.getInetAddress();

String ipString= incomingAddress.getHostAddress();

System.out.println("The incoming address is: " + ipString);

//String Tokenizer is used to extract file name from this class.

StringTokenizer tokens = new StringTokenizer(requestLine);

tokens.nextToken(); // skip over the method, which should be “GET”

String fileName = tokens.nextToken();

// Prepend a “.” so that file request is within the current directory.

fileName = "." + fileName;

String headerLine = null;

while ((headerLine = br.readLine()).length() !e68a843231313335323631343130323136353331333335346134= 0) { //While the header still has text, print it

System.out.println(headerLine);

}

// Open the requested file.

FileInputStream fis = null;

boolean fileExists = true;

try {

fis = new FileInputStream(fileName);

} catch (FileNotFoundException e) {

fileExists = false;

}

//Construct the response message

String statusLine = null; //Set initial values to null

String contentTypeLine = null;

String entityBody = null;

if (fileExists) {

statusLine = "HTTP/1.1 200 OK: ";

contentTypeLine = "Content-Type: " +

contentType(fileName) + CRLF;

} else {

statusLine = "HTTP/1.1 404 Not Found: ";

contentTypeLine = "Content-Type: text/html" + CRLF;

entityBody = "" + "

Not Found" + "Not Found";

}

//End of response message construction

// Send the status line.

os.writeBytes(statusLine);

// Send the content type line.

os.writeBytes(contentTypeLine);

// Send a blank line to indicate the end of the header lines.

os.writeBytes(CRLF);

// Send the entity body.

if (fileExists) {

sendBytes(fis, os);

fis.close();

} else {

os.writeBytes(entityBody);

}

os.close(); //Close streams and socket.

br.close();

socket.close();

}

//Need this one for sendBytes function called in processRequest

private static void sendBytes(FileInputStream fis, OutputStream os)

throws Exception

{

// Construct a 1K buffer to hold bytes on their way to the socket.

byte[] buffer = new byte[1024];

int bytes = 0;

// Copy requested file into the socket’s output stream.

while((bytes = fis.read(buffer)) != -1 ) {

os.write(buffer, 0, bytes);

}

}

private static String contentType(String fileName)

{

if(fileName.endsWith(".htm") || fileName.endsWith(".html"))

return "text/html";

if(fileName.endsWith(".jpg"))

return "text/jpg";

if(fileName.endsWith(".gif"))

return "text/gif";

return "application/octet-stream";

}

}

本回答由提问者推荐

2Q==

已赞过

已踩过<

你对这个回答的评价是?

评论

收起

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值