用java创建一个简单的服务器

class MyService{
	public static void main(String[] args) throws Exception {
	//创建ServerSocket
		ServerSocket server = new ServerSocket(8888);  //设置8888端口
		//监听器等待客户端的请求
		while(true){
			Socket socket = server.accept();
			if(socket!=null){
				//接收到客户端的请求,构建和客户端的数据发送通道
				OutputStream out = socket.getOutputStream(); 
				
			//发送数据给客户端
					//读取本地文件内容
				File file = new File("F:/testwork/july/meta.html");
				FileInputStream in = new FileInputStream(file);
				//定义缓存数组
				byte b[] = new byte[1024];
				int length = 0;
				while((length = in.read(b)) != 0)
					out.write(b,0,length);
					//关闭资源
				in.close();
				out.close();
			}
			
		}
	}
}


Java中创建WebSocket服务器,可以使用Java API for WebSocket(JSR 356)提供的API。以下是创建WebSocket服务器的基本步骤: 1. 创建一个实现了javax.websocket.Endpoint类的WebSocket服务器端点类,并实现onOpen、onClose、onError和onMessage等方法。 ```java import javax.websocket.*; import javax.websocket.server.ServerEndpoint; import java.io.IOException; @ServerEndpoint("/websocket") public class MyWebSocketServer { @OnOpen public void onOpen(Session session) throws IOException { System.out.println("WebSocket opened: " + session.getId()); } @OnClose public void onClose(Session session) throws IOException { System.out.println("WebSocket closed: " + session.getId()); } @OnError public void onError(Session session, Throwable throwable) throws IOException { System.out.println("WebSocket error: " + session.getId()); throwable.printStackTrace(); } @OnMessage public void onMessage(String message, Session session) throws IOException { System.out.println("WebSocket message received: " + message); session.getBasicRemote().sendText("Echo: " + message); } } ``` 2. 在服务器上运行WebSocket服务器端点类。 ```java import javax.websocket.server.ServerEndpointConfig; import org.glassfish.tyrus.server.Server; public class MyWebSocketServerStarter { public static void main(String[] args) { Server server = new Server("localhost", 8888, "/websocket", null, MyWebSocketServer.class); try { server.start(); System.out.println("WebSocket server started at " + server.getUri()); Thread.currentThread().join(); } catch (Exception e) { e.printStackTrace(); } finally { server.stop(); } } } ``` 3. 启动WebSocket服务器,可以使用Java SE提供的内置HTTP服务器或者第三方HTTP服务器(如Tomcat、Jetty等)来启动WebSocket服务器。 以上就是创建WebSocket服务器的基本步骤,您可以根据自己的需求进行修改和扩展。
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值