java 线程的问题

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.PrintWriter;
import java.net.ServerSocket;
import java.net.Socket;
import java.io.*;
public class Server {
public static void main(String[] args)throws Exception{
if(args.length!=1){
System.out.println("用法:<端口>");
}
ServerSocket listen = new ServerSocket(Integer.parseInt(args[0]));
Socket s=listen.accept();
for(;;) {
[color=red]new SThread(s).start();[/color]
}

}
class SThread extends Thread{
    Socket sk;
    SThread(Socket s){
        sk=s;
    }
    public void run(){
    try{
        PrintWriter pw=new PrintWriter(sk.getOutputStream(),true);
        BufferedReader bf=new BufferedReader(new InputStreamReader(sk.getInputStream()));
        System.out.println("aaaaaaaaa");
        String message=null;
        while((message=bf.readLine())!=null){
            System.out.println("收到请求"+message);
            pw.println(message.toUpperCase());
            System.out.println();
        }
        System.out.println("bbbbbbbbbb");
        pw.close();
        bf.close();
        sk.close();

    } catch (NumberFormatException e) {
        // TODO 自动生成 catch 块
        e.printStackTrace();
    } catch (IOException e) {
        // TODO 自动生成 catch 块
        e.printStackTrace();
    }
    }
}

}

红色部分为什么在eclipse3.2里通不过呢?

5个回答

我这里有段Socket通信的代码,希望对你有用
[code="java"]
package org.zergle.test.socket.server;

import java.net.InetAddress;
import java.net.ServerSocket;
import java.net.Socket;
import java.util.Date;
import java.util.ArrayList;
import java.util.List;

/**

  • 服务器
  • @author Johnson Lee
  • */
    public class Server {
    private boolean running;
    private List clients;
    private ServerSocket svrSocket;

    public Server() {
    this.running = true;
    this.clients = new ArrayList();
    }

    public boolean isRunning() {
    return running;
    }

    public void run() {
    try {
    this.svrSocket = new ServerSocket(9090);
    System.err.println("Server started on "
    + new java.sql.Date(new Date().getTime()));
    while (running) {
    Socket cltSocket = this.svrSocket.accept();
    // 保存客户端的连接
    InetAddress ip = cltSocket.getInetAddress();
    int port = cltSocket.getPort();
    ConnectedClient client = new ConnectedClient(ip, port);
    this.clients.add(client);
    System.err.println(ip + " connected.");
    // 为每个客户端开一个线程
    new Thread(new RequestProcessor(this, cltSocket)).start();
    }
    } catch (Exception e) {
    this.running = false;
    }
    }

    /**

    • 连接到服务器端的客户端
    • @author Johnson Lee
    • */
      private static class ConnectedClient {
      public InetAddress ip;
      public int port;

      public ConnectedClient(InetAddress ip, int port) {
      super();
      this.ip = ip;
      this.port = port;
      }

      @Override
      public boolean equals(Object obj) {
      if (obj instanceof ConnectedClient) {
      ConnectedClient c = (ConnectedClient) obj;
      return c.ip.equals(this.ip) && c.port == this.port;
      }
      return false;
      }
      }

    /**

    • @param args */ public static void main(String[] args) { new Server().run(); } } [/code] [code="java"] package org.zergle.test.socket.server;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.PrintWriter;
import java.net.InetAddress;
import java.net.Socket;
import java.net.SocketException;

/**

  • 服务器端用于处理客户连接的处理器
  • @author Johnson Lee
  • */
    public class RequestProcessor implements Runnable {
    private Server server;
    private Socket socket;

    public RequestProcessor(Server server, Socket socket) {
    this.server = server;
    this.socket = socket;
    }

    @Override
    public void run() {
    if (this.server.isRunning() && this.socket != null
    && this.socket.isConnected()) {
    InetAddress ip = this.socket.getInetAddress();
    BufferedReader br = null;
    PrintWriter pw = null;
    String line = null;
    try {
    InputStream is = this.socket.getInputStream();
    br = new BufferedReader(new InputStreamReader(is));
    pw = new PrintWriter(this.socket.getOutputStream(), true);
    while ((line = br.readLine()) != null) {
    System.out.println(line);
    pw.println("服务器自动回复 ^_^ ");
    pw.flush();
    }
    } catch (SocketException e) {
    System.err.println("客户端 " + ip + " 已断开连接");
    } catch (IOException e) {
    e.printStackTrace();
    } finally {
    try {
    if (br != null) {
    br.close();
    br = null;
    }
    } catch (IOException e) {
    }
    }
    }
    }
    }
    [/code]
    [code="java"]
    package org.zergle.test.socket.client;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.OutputStream;
import java.io.PrintWriter;
import java.net.InetSocketAddress;
import java.net.Socket;

/**

  • 客户端
  • @author Johnson Lee
  • */
    public class Client {
    private InetSocketAddress svrAddress;
    private Socket svrSocket;

    public Client(String host, int port) {
    this.svrAddress = new InetSocketAddress(host, port);
    }

    public void connect() throws IOException {
    this.svrSocket = new Socket(svrAddress.getAddress(), svrAddress
    .getPort());
    }

    public boolean isClosed() {
    return this.svrSocket == null || this.svrSocket.isClosed();
    }

    public InputStream getInputStream() throws IOException {
    return this.svrSocket.getInputStream();
    }

    public OutputStream getOutputStream() throws IOException {
    return this.svrSocket.getOutputStream();
    }

    /**

    • @param args */ public static void main(String[] args) { BufferedReader br = null; PrintWriter pw = null; String line = null; try { final Client c = new Client("127.0.0.1", 9090); c.connect();// 连接服务器 try { br = new BufferedReader(new InputStreamReader(System.in)); pw = new PrintWriter(c.getOutputStream(), true); new Thread(new ResponseProcessor(c)).start(); while (!c.isClosed()) { line = br.readLine(); pw.println(line); } } catch (IOException e) { e.printStackTrace(); } finally { try { if (br != null) { br.close(); br = null; } if (pw != null) { pw.close(); pw = null; } } catch (IOException e) { } } } catch (IOException e) { e.printStackTrace(); } }

}
[/code]
[code="java"]
package org.zergle.test.socket.client;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.PrintWriter;
import java.net.SocketException;

/**

  • 服务端响应处理器
  • @author Johnson Lee
  • */
    public class ResponseProcessor implements Runnable {
    private Client client;

    public ResponseProcessor(Client c) {
    super();
    this.client = c;
    }

    @Override
    public void run() {
    BufferedReader br = null;
    PrintWriter pw = null;
    String line = null;
    try {
    br = new BufferedReader(new InputStreamReader(client
    .getInputStream()));
    pw = new PrintWriter(System.out, true);
    while (!client.isClosed()) {
    line = br.readLine();
    pw.println(line);
    }
    } catch (SocketException e) {
    if (!client.isClosed()) {
    System.err.println(e);
    }
    } catch (IOException e) {
    e.printStackTrace();
    }
    }

}
[/code]

[code="java"]for(;;) {
new SThread(s).start();
} [/code]

这是一个死循环,会导致后面的任何代码都不能执行,程序也就无法退出!!

不好意思,看错了。

你的SThread 是内部类,不能那样实例化。这样就可以了:

[code="java"]import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.PrintWriter;
import java.net.ServerSocket;
import java.net.Socket;

public class Server {
public static void main(String[] args) throws Exception {
if (args.length != 1) {
System.out.println("用法:<端口>");
}
ServerSocket listen = new ServerSocket(Integer.parseInt(args[0]));
Socket s = listen.accept();
for (;;) {
new SThread(s).start();
}

}

}

class SThread extends Thread {
Socket sk;

SThread(Socket s) {
    sk = s;
}

public void run() {
    try {
        PrintWriter pw = new PrintWriter(sk.getOutputStream(), true);
        BufferedReader bf = new BufferedReader(new InputStreamReader(sk
                .getInputStream()));
        System.out.println("aaaaaaaaa");
        String message = null;
        while ((message = bf.readLine()) != null) {
            System.out.println("收到请求" + message);
            pw.println(message.toUpperCase());
            System.out.println();
        }
        System.out.println("bbbbbbbbbb");
        pw.close();
        bf.close();
        sk.close();

    } catch (NumberFormatException e) {
        // TODO 自动生成 catch 块
        e.printStackTrace();
    } catch (IOException e) {
        // TODO 自动生成 catch 块
        e.printStackTrace();
    }
}

}[/code]

或者Main方法这样写:(内部类的实例化)
[code="java"] public static void main(String[] args) throws Exception {
Server server = new Server();
if (args.length != 1) {
System.out.println("用法:<端口>");
}
ServerSocket listen = new ServerSocket(Integer.parseInt(args[0]));
Socket s = listen.accept();
for (;;) {
server.new SThread(s).start();
}

}[/code]

final Socket s=listen.accept();

Csdn user default icon
上传中...
上传图片
插入图片
抄袭、复制答案,以达到刷声望分或其他目的的行为,在CSDN问答是严格禁止的,一经发现立刻封号。是时候展现真正的技术了!
立即提问