gpt4 book ai didi

java - 如何在jsp中实现客户端和服务器代码

转载 作者:行者123 更新时间:2023-11-30 03:56:55 25 4
gpt4 key购买 nike

我在 Java SE 中有一个用于 Desktop 的小型聊天应用程序,我也想为 Web 实现相同的应用程序,我有 ChatServer为:

public class ChatServer extends Thread {
public static final int DEFAULT_PORT = 6035;


public static String initServer() {
String msg = "";
int port = DEFAULT_PORT;
ServerSocket serverSocket = null;
Socket socket = null;
try {
serverSocket = new ServerSocket(port);
msg = "Listening on port " + port;
while (true) {
socket = serverSocket.accept();
/*System.out.println("Connection receive from "
+ socket.getRemoteSocketAddress());*/
ChatHandler handler = new ChatHandler(socket);
handler.start();
}


} catch (IOException ioe) {
System.err.println("Usage: java ChatServer [port]");
System.err.println("Where options include:");
System.err.println("\tport the port on which to listen.");
msg = "Usage: java ChatServer [port]";
System.exit(0);
} finally {
try {
serverSocket.close();
} catch (IOException ioe) {
ioe.printStackTrace();
}
}

return msg;
}
}

现在要在 index.jsp 中调用它,我有:

<%@ page language="java" contentType="text/html; charset=UTF-8"
pageEncoding="UTF-8"%>
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<title>Insert title here</title>
</head>
<body>
<h1><%=pkj.com.lenvel.ChatServer.initServer() %></h1>
</body>
</html>

上面的代码没有显示任何消息,我仍然很困惑,在哪里实现Client的代码?

最佳答案

试试这个

服务器(YourServer.java)

import java.io.*;
import java.net.*;

public class YourServer
{
public static void main(String[] args )
{
try {
ServerSocket socket = new ServerSocket(8765);

Socket insocket = socket.accept( );

BufferedReader in = new BufferedReader (new
InputStreamReader(insocket.getInputStream()));
PrintWriter out = new PrintWriter (insocket.getOutputStream(),
true);

String instring = in.readLine();
out.println("The server got this: " + instring);
insocket.close();
}
catch (Exception e) {}
}
}

Client.Jsp

<%@ page import="java.io.*, java.net.*" %>
<HTML>
<HEAD>
<TITLE>Creating Client/Server Applications</TITLE>
</HEAD>
<BODY>
<H1>Creating Client/Server Applications</H1>
<%
try{
int character;
Socket socket = new Socket("127.0.0.1", 8765);
InputStream inSocket = socket.getInputStream();
OutputStream outSocket = socket.getOutputStream();
String str = "Hello!\n";
byte buffer[] = str.getBytes();
outSocket.write(buffer);
while ((character = inSocket.read()) != -1) {
out.print((char) character);
}
socket.close();
}
catch(java.net.ConnectException e){
%>
You must first start the server application
(YourServer.java) at the command prompt.
<%
}
%>
</BODY>
</HTML>

Taken from this link

关于java - 如何在jsp中实现客户端和服务器代码,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/22930480/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com