我遇到了一些问题,试图用java制作一个客户端/服务器系统,下一个代码属于客户端......
public class ClientTCP {
final static int PORT = 65001;
Socket _socket;
private void fireUp(){
String message = "";
BufferedReader bfi = null;
BufferedReader bfr = null;
PrintWriter writer = null;
try{
InetAddress address = InetAddress.getByName("localhost");
_socket = new Socket(address,PUERTO);
bfr = new BufferedReader(
new InputStreamReader(System.in));
bfi = new BufferedReader(
new InputStreamReader(_socket.getInputStream()));
System.out.println("Enter some data");
String inputstr = bfr.readLine();
writer = new PrintWriter(_socket.getOutputStream(),true);
writer.println(inputstr);
if((message = bfi.readLine()) != null){
Logger.getLogger(ClientTCP.class.getName()).log(Level.INFO,message);
}
}catch(IOException ioex){
ioex.printStackTrace();
}finally{
if(_socket != null){
try {
_socket.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
}
...而这个属于服务器,并且为每个客户端创建的线程:
public class ServerrTCP {
static int SEC = 0;
final static int PORT = 65001;
Socket _socket;
ServerSocket _ssocket;
private void fireUp(){
try{
_socket = new Socket();
_ssocket = new ServerSocket(PORT);
while(true){
_socket = _ssocket.accept();
new ClientThreads(_socket,SEC++);
}
}catch(IOException ioex){
Logger.getLogger(ServerTCP.class.getName()).log(Level.SEVERE,null,ioex);
}
线程创建类...
public class ClientThreads extends Thread{
int _id;
Socket _socket;
public ClientThreads(Socket socket, int id){
super();
_socket = socket;
_id = id;
this.start();
}
@Override
public void run(){
String strinput;
BufferedReader bfr = null;
PrintWriter writer = null;
try{
bfr = new BufferedReader(
new InputStreamReader(_socket.getInputStream()));
writer = new PrintWriter(
_socket.getOutputStream(),true);
while((strinput = bfr.readLine()) != null){
System.out.println("The user "+ _id +" wrote "+ strinput);
}
writer.println("Thanks, user " + _id);
}catch(IOException ioex){
ioex.printStackTrace();
}
}
}
抱歉代码量很大,但由于这个问题我要疯了,我认为我出错的地方是粗体字,我认为它会在阻塞 I/O 时产生某种问题,但我不知道为什么,以及如何解决它,提前谢谢