套接字编程中的连接错误

时间:2015-12-09 17:23:06

标签: java sockets server client

我在网络课上做了一个项目,我在代码中遇到了问题。那是我的代码不接受连接。在图片中你可以看到问题,这里是代码:

import java.io.BufferedReader;
import java.io.InputStreamReader;
import java.io.PrintWriter;
import java.net.ServerSocket;
import java.net.Socket;

public class WebServer {
public static void main(String args[]) {
WebServer ws = new WebServer();
ws.start();
}

protected void start() {
ServerSocket s;
Socket remote;

System.out.println("Webserver starting up on port 8080");

try {

  s = new ServerSocket(8080);

} catch (Exception e) {
  System.out.println("Error: " + e);
  return;
}

  try {
      System.out.println("Waiting for connection ");
     remote = s.accept();
    System.out.println("Connection, sending data. ");
    BufferedReader in = new BufferedReader(new InputStreamReader(
    remote.getInputStream()));
    PrintWriter out = new PrintWriter(remote.getOutputStream());


    String str = ".";
    while (!str.equals("")){
      str = in.readLine();
    }

    out.println("HTTP/1.0 200 OK");
    out.println("Content-Type: text/html");
    out.println("Server: Bot");

    out.println("");

    out.println("<H1>Welcome to the Ultra Mini-WebServer</H2>");
    out.flush();
    remote.close();
  } catch (Exception e) {
    System.out.println("Error: " + e);
  }

  }
  }

我认为接受功能存在问题?或者我应该还实现recv功能?我需要代码的enter image description here是客户端和Web服务器之间的聊天。

2 个答案:

答案 0 :(得分:0)

此代码发送一个jpeg文件,对我来说很好用:

public class FileServer { 
    static BufferedInputStream bis;
    static BufferedOutputStream bos = null;
    static ServerSocket ss = null;
    static Socket s = null;
    static int handler = 0;
    static byte[] buffer= new byte[1024];

    public static void main(String[] args)throws IOException  {
            ss = new ServerSocket(1234);
            System.out.println("Waiting");
            s = ss.accept();


            bis = new BufferedInputStream(new FileInputStream("b.jpg"));
            bos = new BufferedOutputStream(s.getOutputStream( ));
            while((handler= bis.read(buffer))!=-1){
                    bos.write(buffer,0,handler);
                    System.out.println("Sending");
            }
            System.out.println("File Written Successfully");
            bis.close();
            bos.close();

    }  
}

答案 1 :(得分:0)

  

这是我的代码不接受连接。

您的代码正在接受连接。当我尝试e。 G。 nc localhost 8080,我得到

Webserver starting up on port 8080
Waiting for connection 
Connection, sending data. 

因此,问题必须出在您的客户端或去往服务器的路上。