客户端:
public class tranClient {
public static void main(String[] args) {
Socket s=null;
BufferedReader bufr=null;
try {
//1,建立socket客户端
s=new Socket("192.168.56.1",10005);
//获取键盘输入
bufr=new BufferedReader(new InputStreamReader(System.in));
//写出socket流,发给服务器
BufferedWriter buOut=new BufferedWriter(new OutputStreamWriter(s.getOutputStream()));
//读取服务器数据
BufferedReader buIn=new BufferedReader(new InputStreamReader(s.getInputStream()));
String line=null;
while((line=bufr.readLine())!=null){
if(line.equals("over"))
break;
buOut.write(line);
buOut.newLine();
buOut.flush();
String str=buIn.readLine();
System.out.println("server::"+str);
}
} catch (UnknownHostException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}finally{
try {
s.close();
} catch (IOException e) {
e.printStackTrace();
}
try {
if(bufr!=null)
bufr.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
}
服务端:
public class transServer {
public static void main(String[] args) {
ServerSocket ss=null;
BufferedReader bufr=null;
try {
ss=new ServerSocket(10005);
Socket s=ss.accept();
String id=s.getInetAddress().getHostAddress();
System.out.println(id+".....connected");
//获取客户端的数据
bufr=new BufferedReader(new InputStreamReader(s.getInputStream()));
//发送数据给客户端
BufferedWriter buOut=new BufferedWriter(new OutputStreamWriter(s.getOutputStream()));
String line=null;
while((line=bufr.readLine())!=null){
buOut.write(line.toUpperCase());
buOut.newLine();
buOut.flush();
System.out.println(line);
}
} catch (IOException e) {
e.printStackTrace();
}finally{
try {
ss.close();
} catch (IOException e) {
e.printStackTrace();
}
try {
if(bufr!=null)
bufr.close();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
} |
|