本帖最后由 whocases 于 2012-6-29 11:53 编辑
Server端:
import java.net.*;
import java.io.*;
public class TestServer
{
public static void main(String[] args)
{
try {
InputStream in = null;
OutputStream out = null;
ServerSocket ss = new ServerSocket(5555);
while(true)
{
Socket s1 = ss.accept();
System.out.println(s1.getPort() + " a Client!");
in = s1.getInputStream();
out = s1.getOutputStream();
InputStreamReader isr = new InputStreamReader(in);
BufferedReader isread = new BufferedReader(isr);
OutputStreamWriter osr = new OutputStreamWriter(out);
PrintWriter pw = new PrintWriter(osr);
InputStreamReader str = new InputStreamReader(System.in);
BufferedReader str1 = new BufferedReader(str); //建立2个管道
System.out.println("Client : " + isread.readLine()); //从client读入一行
String line = str1.readLine(); //从命令行读一行
while(!(line.equals("bye"))) //循环,读入的不是bye就继续通信
{
pw.println(line);
System.out.println("Server : " + line);
System.out.println("Client : " + isread.readLine());
line = str1.readLine();
}
pw.close();
isread.close();
str1.close();
s1.close();
}
} catch(IOException e) {}
}
}
Client端:
import java.net.*;
import java.io.*;
public class TestClient
{
public static void main(String[] args)
{
try {
InputStream in = null;
OutputStream out = null;
Socket s1 = new Socket("127.0.0.1",5555);
in = s1.getInputStream();
out = s1.getOutputStream();
InputStreamReader isr = new InputStreamReader(in);
BufferedReader isread = new BufferedReader(isr);
OutputStreamWriter osr = new OutputStreamWriter(out);
PrintWriter pw = new PrintWriter(osr);
InputStreamReader str = new InputStreamReader(System.in);
BufferedReader str1 = new BufferedReader(str);
String readline = str1.readLine();
while(!(readline.equals("bye")))
{
pw.println(readline);
System.out.println("Client : " + readline);
System.out.println("Server : " + isread.readLine());
readline = str1.readLine();
}
isread.close();
pw.close();
s1.close();
} catch(IOException e) {}
}
}
我的这个程序server端接收不到client传送过来的数据,但是在打印bye时能停止。请哪位高手帮忙看一下,3Q~~ |
|