无法从远程服务器接收响应

时间:2016-08-08 16:04:37

标签: java sockets connection datainputstream

我正在尝试编写一个代码,允许我连接到远程服务器并从中接收响应。 远程地址是:www.euref-ip.net:2101

尝试从网页连接时,它可以正常工作。但是当我试图通过我的java代码连接时,我无法得到任何回复。 到目前为止,这是我的代码:

set(('foo', 'bar'))

现在public class Client implements Runnable{ private String nServer = ""; private int nPort = 0; public Client(String server, int port){ this.nServer = server; this.nPort = port; } @Override public void run() { try { SocketAddress sockaddr = new InetSocketAddress(nServer, nPort); Socket s = new Socket(); s.connect(sockaddr, 10 * 1000); if (s.isConnected()) { s.setSoTimeout(20 * 1000); DataOutputStream out = new DataOutputStream (s.getOutputStream()); DataInputStream in = new DataInputStream (s.getInputStream()); while (true) { // send a message to the server String requestmsg = "GET / HTTP/1.0\r\n"; requestmsg += "User-Agent: Client v1\r\n"; requestmsg += "Accept: */* \r\n"; requestmsg += "Connection: keep alive\r\n"; out.write(requestmsg.getBytes()); out.flush(); // receive a response int ln = in.available(); byte [] bytes = new byte [ln]; in.read(bytes); System.out.println(new String(bytes) + "\n"); Thread.sleep(2000); } } } catch (UnknownHostException ex) {System.out.println(ex);} catch (IOException ex) {System.out.println(ex);} catch (InterruptedException ex) {System.out.println(ex);} }} 变量始终为0,我正在读取空响应。 我究竟做错了什么?有什么建议? 任何帮助,将不胜感激。

1 个答案:

答案 0 :(得分:0)

您的HTTP请求不完整,您需要在末尾添加一个额外的空行,表示标题部分的结尾,此处也是请求的结尾。

试试这个:

var List = React.createClass({
  handleClick (id) {
    console.log('yaaay the item key was: ', id)
  }

  render() {
    return (
      <ul>
        {this.props.items.map(item =>
          <ListItem key={item.id} item={item} onItemClick={this.handleClick} />
        )}
      </ul>
    );
  }
});

var ListItem = React.createClass({
  render() {
    return (
      <li onClick={this._onClick}>
        ...
      </li>
    );
  },
  _onClick() {
    this.props.onItemClick(this.props.item.id);
  }
});