问题是这样的:我使用ServerSocket和Socket类创建了一个Java Server。 html页面正确显示,但是我不知道如何将数据(从输入类型=文本)发送到java服务器,然后显示我在另一个html页面上编写的消息。
代码如下:
MyServer类:
private int port;
private ServerSocket ss;
private Socket s;
private PrintWriter pw;
public MyServer(){
port = 1245;
try{
ss = new ServerSocket(port);
System.out.println("server creato");
}
catch(Exception e){
e.printStackTrace();
}
listen();
}
public void listen(){
try{
while(true){
s = ss.accept();
System.out.println("OK");
if(s == null)
System.exit(1);
Client c = new Client(s);
c.start();
}
}catch(Exception e){
e.printStackTrace();
}
}
客户端类(扩展线程):
public Client(Socket s){
this.s = s;
try{
pw = new PrintWriter(s.getOutputStream(), true);
br = new BufferedReader(new InputStreamReader(s.getInputStream()));
f = new File("test.html");
}catch(Exception e){
e.printStackTrace();
}
}
public BufferedReader getBr(){
return this.br;
}
public PrintWriter getPw(){
return this.pw;
}
public File getF(){
return this.f;
}
public void displayHtml(){
try {
FileInputStream fis = new FileInputStream(f);
BufferedReader br2 = new BufferedReader(new InputStreamReader(fis));
StringBuilder sb = new StringBuilder();
String ris = null;
while((ris = br2.readLine()) != null){
sb.append(ris);
//sb.append("\r\n");
}
pw.println("HTTP/1.1 200 OK");
pw.println("Content-Type: text/html");
pw.println("\r\n");
pw.println(sb.toString());
pw.flush();
s.close();
}catch(Exception e){
e.printStackTrace();
}
}
public void
public void run(){
try{
displayHtml();
}catch(Exception e){
e.printStackTrace();
}
}
}
最后是Main类:
public static void main(String[] args){
MyServer ms = new MyServer();
}
我正在寻找一个好的解决方案。我希望不要删除我的所有代码。谢谢:)