【发布时间】:2014-03-09 11:07:31
【问题描述】:
我无法解决关于“服务器已添加空值”的问题。 它不会先进入菜单来处理数据。
这也类似于编写客户端到服务器的问题。
这是我的代码:
学生:
import java.lang.*;
import java.io.*;
import java.net.*;
import java.util.*;
public class Student {
public static void main(String args[]) {
PrintWriter out = null;
Scanner sc = new Scanner (System.in);
//initialization
String student = " ";
String id = " ";
String name = " ";
try {
Socket skt = new Socket("localhost", 1234);
out = new PrintWriter(skt.getOutputStream(), true);
while (name.equals("exit")) { //never ending menu
System.out.print("Please enter name: ");
name = sc.nextLine();
System.out.print("Please enter ID Number: ");
id = sc.nextLine();
student = name +" - "+ id;
out.print(student);
}
} catch(Exception e) {
System.out.println("Whoops! It didn't work.");
} finally {
if (out != null) {
try {
out.close();
} catch (Exception e) {
}
}
}
}
}
服务器:
import java.lang.*;
import java.io.*;
import java.net.*;
import java.util.*;
public class Server {
public static void main(String args[]) {
Scanner sc = new Scanner (System.in);
ArrayList<String> collector = new ArrayList<String>();
String x = "";
try {
ServerSocket srvr = new ServerSocket(1234);
Socket skt = srvr.accept();
BufferedReader in = new BufferedReader(new InputStreamReader(skt.getInputStream()));
x = in.readLine();
collector.add(x);
System.out.println("Server has added "+collector.get(collector.size()-1));
}
catch(Exception e) {
e.printStackTrace();
System.out.print("Whoops! It didn't work!\n");
}
}
}
知道有什么问题吗?
【问题讨论】: