最近初步学习java socket 编程的时候遇到一个问题就是,当客户端向服务端发送数据时,会出现不能输入也不能,程序卡住的现象,尤其是中文,最多输入两行,控制台就不能再输入数据(客户端输入是用system.in来从键盘获取数据)。英文字符还好一些,但也会出现此种状况,百思不得其解!代码如下:[code="java"][/code]
server:
package dragon.socket;
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 MyServer {
/**
* @param args
* @throws IOException
*/
public static void main(String[] args) throws IOException {
// TODO Auto-generated method stub
ServerSocket ss = null;
PrintWriter out = null;
BufferedReader in = null;
try {
ss = new ServerSocket(1111);
} catch (IOException e) {
// TODO Auto-generated catch block
System.err.println("could not listen port:1111");
System.exit(1);
e.printStackTrace();
}
Socket inComing = null;
while(true){
inComing = ss.accept();
out = new PrintWriter(inComing.getOutputStream(),true);
in = new BufferedReader(new InputStreamReader(inComing.getInputStream(),"GBK"));
out.println("hello!....");
out.println("enter BYE to exit");
out.flush();
while(true){
String str = in.readLine();
if(str==null){
break;
}
else{
out.println("Echo:"+str);
System.out.println(str);
out.flush();
if(str.trim().equalsIgnoreCase("BYE")){
break;
}
}
}
out.close();
inComing.close();
ss.close();
}
}
}
client:
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.PrintWriter;
import java.net.Socket;
import java.net.UnknownHostException;
public class Client {
public static void main(String[] args) throws IOException {
Socket s = null;
PrintWriter out = null;
BufferedReader in = null;
try {
s = new Socket("localhost", 1111);
out = new PrintWriter(s.getOutputStream(),true);
in = new BufferedReader(new InputStreamReader(s.getInputStream()));
} catch (UnknownHostException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
System.out.println(in.readLine());
System.out.println(in.readLine());
BufferedReader stdln = new BufferedReader(new InputStreamReader(System.in));
String userInput;
while((userInput=stdln.readLine())!=null){
out.println(userInput);
System.out.println(in.readLine());
}
out.close();
in.close();
s.close();
}
}