java socket通讯交互
Recently,I was studing the linux OS (redhat 9),involving the java net.The server-side is in the linux OS ,and the Client-side is in windows OS .The code is here:
Server-side
![](https://images.cnblogs.com/OutliningIndicators/ContractedBlock.gif)
1 import java.io.*; 2 import java.net.*; 3 public class HelloServerTest { 4 5 public static void main(String[] args) { 6 try { 7 //创建ServerSocket 8 ServerSocket ss=new ServerSocket(8888); 9 System.out.println("I am listening"); 10 11 Socket s=ss.accept(); 12 13 //可以从客户端读取消息 14 InputStreamReader isr=new InputStreamReader(s.getInputStream()); 15 BufferedReader br=new BufferedReader(isr); 16 String kk=br.readLine(); 17 System.out.println("客户端传过来的消息是:"+kk); 18 System.out.println(" the message from client is :"+kk); 19 20 OutputStreamWriter osw=new OutputStreamWriter(s.getOutputStream()); 21 PrintWriter pw=new PrintWriter(osw,true); 22 pw.println("message from the server"); 23 } catch (Exception e) { 24 // TODO: handle exception 25 } 26 } 27 28 }
Client-side
![](https://images.cnblogs.com/OutliningIndicators/ContractedBlock.gif)
1 import java.io.*; 2 import java.net.*; 3 public class ClientTest { 4 5 public static void main(String[] args) { 6 // TODO Auto-generated method stub 7 try { 8 //连接ip 和port 9 Socket s=new Socket("192.168.148.10",8888); 10 OutputStreamWriter osw=new OutputStreamWriter(s.getOutputStream()); 11 BufferedWriter bw=new BufferedWriter(osw); 12 PrintWriter pw=new PrintWriter(bw,true); 13 pw.println("Hello,zouteng,java net"); 14 15 InputStreamReader isr=new InputStreamReader(s.getInputStream()); 16 BufferedReader breader=new BufferedReader(isr); 17 String kk=breader.readLine(); 18 System.out.println("服务器反馈的信息: "+kk); 19 } catch (UnknownHostException e) { 20 // TODO Auto-generated catch block 21 e.printStackTrace(); 22 } catch (IOException e) { 23 // TODO Auto-generated catch block 24 e.printStackTrace(); 25 } 26 } 27 28 }