Java Socket in.readLine NULL
这是我第一次学习使用插座。我遇到了一些我不能理解的问题 我只是不知道为什么server类中的in.readLine()总是为null,而client类中的操作永远不会执行 这是服务器类:(我没有显示导入,它们是正确的) 公共类设置服务器{Java Socket in.readLine NULL,java,sockets,serversocket,Java,Sockets,Serversocket,这是我第一次学习使用插座。我遇到了一些我不能理解的问题 我只是不知道为什么server类中的in.readLine()总是为null,而client类中的操作永远不会执行 这是服务器类:(我没有显示导入,它们是正确的) 公共类设置服务器{ public static void main(String[] args) throws IOException { System.out.println("The game server is running."); ServerSocke
public static void main(String[] args) throws IOException {
System.out.println("The game server is running.");
ServerSocket listener = new ServerSocket(9898);
try{
while(true){
new Game(listener.accept()).start();
}
} finally{
listener.close();
}
}
private static class Game extends Thread{
private Socket socket;
public Game(Socket s){
socket = s;
}
public void run(){
try{
// Decorate the streams so we can send characters
// and not just bytes. Ensure output is flushed
// after every newline.
BufferedReader in = new BufferedReader(new InputStreamReader(socket.getInputStream()));
PrintWriter out = new PrintWriter(socket.getOutputStream(), true);
out.println("You have 60 seconds every turn, get as high socre as possible");//to client
out.println("Every time, type the index of cards you choose in such way \"xx,xx,xx(xx=1~15)\"Get Ready");//to client
out.println("Game begins!");//to client
//initialize a game
CardsShown oneGame = new CardsShown();
out.println(oneGame.toString());//to client
long startTime = System.currentTimeMillis();
while(true){
long currentTime = System.currentTimeMillis();
if(currentTime - startTime > 1800000)
break;
String input = in.readLine();//from client
if(input == null)break;
String[] words = input.split(",");
int[] index = new int[words.length];
for(int i = 0; i < words.length; i++)
index[i] = Integer.parseInt(words[i]);
boolean tmp = oneGame.isSet(index);
out.println(tmp);//to client, tell him if he is right or not
if(tmp){
// firstly, remove the three cards
for(int i = 0; i < 3; i++)
oneGame.cards.remove(new Integer(index[i]));
oneGame.setState(oneGame.getState() - 3);
//make up with three new cards
try {
if(oneGame.getState() == 9)
oneGame.fixTo12Cards();
if(!oneGame.setExist())
oneGame.fixTo15Cards();
} catch (Exception e) {
e.printStackTrace();
}
out.println(oneGame.toString());//to client, only after the last chose of client is right
}
}
out.println("Time Out");//to client
}catch(IOException e){
System.out.println("Error handling " + e);
}finally{
try {
socket.close();
}catch (IOException e) {
System.out.println("Couldn't close a socket, what's going on?");
}
}
}
}
publicstaticvoidmain(字符串[]args)引发IOException{
System.out.println(“游戏服务器正在运行”);
ServerSocket侦听器=新的ServerSocket(9898);
试一试{
while(true){
新游戏(listener.accept()).start();
}
}最后{
listener.close();
}
}
私有静态类游戏扩展线程{
专用插座;
公共游戏(s){
插座=s;
}
公开募捐{
试一试{
//装饰流以便我们可以发送字符
//不仅仅是字节。确保刷新输出
//每次换行之后。
BufferedReader in=新的BufferedReader(新的InputStreamReader(socket.getInputStream());
PrintWriter out=新的PrintWriter(socket.getOutputStream(),true);
println(“你每回合有60秒,尽可能提高分数”);//发送给客户机
out.println(“每次,键入您选择的卡片索引\“xx,xx,xx(xx=1~15)\“准备就绪”);//发送给客户
out.println(“游戏开始!”;//发送给客户端
//初始化游戏
CardsShown oneGame=新的CardsShown();
out.println(oneGame.toString());//发送给客户端
long startTime=System.currentTimeMillis();
while(true){
长currentTime=System.currentTimeMillis();
如果(当前时间-开始时间>1800000)
打破
String input=in.readLine();//来自客户端
如果(输入==null)中断;
String[]words=input.split(“,”);
int[]索引=新的int[words.length];
for(int i=0;i
}
这是客户端类:
公共类SetClient{
public int score;
private BufferedReader in;
private PrintWriter out;
private static int PORT = 9898;
private Socket socket;
private JFrame frame = new JFrame("Game Client");
private JTextField dataField = new JTextField(40);
private JTextArea messageArea = new JTextArea(8, 60);
private JTextArea cardsArea = new JTextArea(8, 60);
public SetClient() throws Exception{
score = 0;
// Layout GUI
messageArea.setEditable(false);
cardsArea.setEditable(false);
frame.getContentPane().add(dataField, "North");
frame.getContentPane().add(new JScrollPane(messageArea), "Center");// for response from server
frame.getContentPane().add(new JScrollPane(cardsArea), "South");// for showing the cards
// Add Listeners
dataField.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
System.out.println(score);
System.out.println(dataField.getText());
out.println(dataField.getText());//to server
String response;
try {
response = in.readLine();
if (response.equals("Time Out")) {
System.exit(0);
}
else if(response.equals("true")){
score++;
response = response + "\n" + "You got one point!";
cardsArea.setText("");
cardsArea.append(in.readLine() + "\n");
}
} catch (IOException ex) {
response = "Error: " + ex;
}
messageArea.append(response + "\n");
dataField.selectAll();
}
});
}
public void play() throws IOException{
// Get the server address from a dialog box.
String serverAddress = JOptionPane.showInputDialog(
frame,
"Enter IP Address of the Server:",
"Welcome to the Set Game!",
JOptionPane.QUESTION_MESSAGE);
// Make connection and initialize streams
Socket socket = new Socket(serverAddress, PORT);
in = new BufferedReader(
new InputStreamReader(socket.getInputStream()));
out = new PrintWriter(socket.getOutputStream(), true);
for(int i = 0; i < 3; i++)
messageArea.append(in.readLine() + "\n");
cardsArea.append(in.readLine() + "\n");
}
private boolean wantsToPlayAgain() {
int response = JOptionPane.showConfirmDialog(frame,
"Want to play again?",
"Set Game",
JOptionPane.YES_NO_OPTION);
frame.dispose();
return response == JOptionPane.YES_OPTION;
}
public static void main(String[] args) throws Exception {
while(true){
SetClient client = new SetClient();
client.frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
client.frame.pack();
client.frame.setVisible(true);
client.play();
if (!client.wantsToPlayAgain()) {
break;
}
}
}
public int评分;
中的私有缓冲区读取器;
私人打印输出;
专用静态int端口=9898;
专用插座;
私有JFrame=新JFrame(“游戏客户端”);
私有JTextField数据字段=新JTextField(40);
私有JTextArea messageArea=新的JTextArea(8,60);
私人JTextArea cardsArea=新JTextArea(8,60);
public SetClient()引发异常{
得分=0;
//布局图形用户界面
messageArea.setEditable(false);
cardsArea.setEditable(false);
frame.getContentPane().add(数据字段,“北”);
frame.getContentPane().add(新的JScrollPane(messageArea),“Center”);//用于服务器的响应
frame.getContentPane().add(新的JScrollPane(cardsArea),“South”);//用于显示卡
//添加侦听器
addActionListener(新ActionListener(){
已执行的公共无效操作(操作事件e){
系统输出打印项次(分数);
System.out.println(dataField.getText());
out.println(dataField.getText());//到服务器
字符串响应;
试一试{
response=in.readLine();
if(响应等于(“超时”)){
系统出口(0);
}
else if(response.equals(“true”)){
分数++;
response=response+“\n”+“你得了一分!”;
cardsArea.setText(“”);
cardsArea.append(in.readLine()+“\n”);
}
}捕获(IOEX异常){
response=“Error:”+ex;
}
messageArea.append(响应+“\n”);
dataField.selectAll();
}
});
}
public void play()引发IOException{
//从对话框中获取服务器地址。
字符串serverAddress=JOptionPane.showInputDialog(
框架
“输入服务器的IP地址:”,
“欢迎来到布景游戏!”,
JOptionPane.QUESTION_消息);
//建立连接并初始化流
套接字=新套接字(服务器地址、端口);
in=新的缓冲读取器(
新的InputStreamReader(socket.getInputStream());
out=新的PrintWriter(socket.getOutputStream(),true);
对于(int i=0;i<3;i++)
messageArea.append(in.readLine()+“\n”);
cardsArea.append(in.readLine()+“\n”);
}
私有布尔值WantStopLayReach(){
int响应