服务器
public class Server {
class ServerHelper implements Runnable
{
InputStream is;
private InputStreamReader isr;
private BufferedReader br;
public ServerHelper(InputStream is) {
this.is = is;
isr = new InputStreamReader(is);
br = new BufferedReader(isr);
}
private void display() throws IOException {
String s = "";
System.out.print("client says : ");
while ( ( s = br.readLine() ) != null ) {
System.out.print(s + " ");
}
}
@Override
public void run() {
try {
display( );
} catch (IOException ex) {
Logger.getLogger(Server.class.getName()).log(Level.SEVERE, null, ex);
}
}
void start( ) throws Exception{
ServerSocket ss = new ServerSocket(5555);
while (true) {
System.out.println("waiting for conn..");
Socket accept = ss.accept();//code hangs over here and doesn't proceed ahead
if( accept == null )
System.out.println("got null...");
System.out.println("got the client req...");
ServerHelper sh = new ServerHelper(accept.getInputStream());
Thread t = new Thread(sh);
t.start();
}
}
public static void main(String[] args) {
try {
// TODO code application logic here
new Server().start();
} catch (Exception ex) {
Logger.getLogger(Server.class.getName()).log(Level.SEVERE, null, ex);
}
}
客户
public class Client {
void start( ) throws Exception{
System.out.println("enter window size ");
Scanner sc = new Scanner(System.in);
int wsize = sc.nextInt();
Socket s = new Socket("127.0.0.1", 5555);
System.out.println("is connected .." + s.isConnected());
OutputStream outputStream = s.getOutputStream();
PrintWriter pw = new PrintWriter(outputStream);
String c = "y";
int j = 0;
do{
String se = "";
for (int i = 0; i < wsize; i++) {
j++;
se = se + String.valueOf(j);
}
pw.println(se);
pw.flush();
System.out.println("do u wanna send more....?(y|n)");
c = sc.next();
}while( c.equalsIgnoreCase("y") );
}
public static void main(String[] args) {
try {
// TODO code application logic here
new Client().start();
} catch (Exception ex) {
Logger.getLogger(Client.class.getName()).log(Level.SEVERE, null, ex);
}
}
}
Socket accept = ss.accept();
在这里我的代码挂断了我知道它正在阻止 io,但是在客户端我确实验证了客户端是否已连接但它显示已连接...accept() 有什么问题?我为我所有的 TCP 应用程序都以类似的方式编码,但这很奇怪..任何人都可以帮忙
我还为那些想看看那个类的人添加了 ServerHelper 代码。