自己编写的一个简单服务器与客户端
服务器代码如下package first;
//msa1.java
import java.io.*;
import java.net.*;
public class service {
public static void main(String args[]) {
try {
ServerSocket ss = new ServerSocket(4321);
System.out.println("Server OK");
while (true) {
Socket s = ss.accept();
serv p = new serv(s);
Thread t = new Thread(p);
t.start();
}
} catch (IOException e) {
}
}
}
class serv implements Runnable {
Socket s;
static int i;
public serv(Socket s1) {
s = s1;
}
public void run() {
try {
BufferedReader in = new BufferedReader(new InputStreamReader(
s.getInputStream()));
// String info = in.readLine();
++i;// 用静态变量记录来访者的个数
String s1;
s1 = in.readLine();
System.out.println(s1 + " " + i);
PrintStream out = new PrintStream(s.getOutputStream());
out.println("nihao");
in.close();
out.close();
s.close();
} catch (IOException e) {
}
}
}
客户端代码如下:
package first;
//mca.java
import java.io.*;
import java.net.*;
public class client {
public static void main(String args[]) {
try {
Socket s = new Socket(InetAddress.getLocalHost(), 4321);
String x = null;
PrintStream out = new PrintStream(s.getOutputStream());
String c = "txt1.txt";
out.println(c);
InputStreamReader ins = new InputStreamReader(s.getInputStream());
BufferedReader in = new BufferedReader(ins);
x = in.readLine();
System.out.println(x);
out.close();
in.close();
s.close();
} catch (IOException e) {
}
}
}
现在是没有问题的,但如果我把服务器的如下代码
s1 = in.readLine();
System.out.println(s1 + " " + i);
改为
while ((s1 = in.readLine()) != null)
System.out.println(s1 + " " + i);
客户端代码
x = in.readLine();System.out.println(x);
改为
while ((x = in.readLine()) != null) System.out.println(x);