标签:
1.服务器端
import java.io.BufferedReader; import java.io.IOException; import java.io.InputStream; import java.io.InputStreamReader; import java.net.ServerSocket; import java.net.Socket; public class HelloWorldServer { public static void main(String[] args) { ServerSocket server = null; BufferedReader reader = null; Socket client = null; try { server = new ServerSocket(9000);//创建ServerSocket对象,并绑定端口 client = server.accept();//调用accept方法,等待客户端的连接 InputStream in = client.getInputStream(); reader = new BufferedReader(new InputStreamReader(in)); String str = reader.readLine(); System.out.println(str); } catch (IOException e) { e.printStackTrace(); }finally{ try{ if(client!=null){ client.close(); } }catch(IOException e){ e.printStackTrace(); } } } }
2.客户端
import java.io.IOException; import java.io.OutputStream; import java.io.PrintWriter; import java.net.Socket; import java.net.UnknownHostException; import java.util.Scanner; public class HelloWorldClient { public static void main(String[] args) { Socket client = null; PrintWriter writer = null; try { client = new Socket("www.feifeishi.cn", 9000);//www.feifeishi.cn是我的云服务器 OutputStream out = client.getOutputStream(); writer = new PrintWriter(out); Scanner sc=new Scanner(System.in); String aa=sc.nextLine(); writer.print(aa); writer.flush(); } catch (UnknownHostException e) { e.printStackTrace(); } catch (IOException e) { e.printStackTrace(); }finally{ try{ if(writer!=null){ writer.close(); } if(client!=null){ client.close(); } }catch(IOException e){ e.printStackTrace(); } } } }
3.运行
将服务器端放到服务器上并运行
运行服务器端
正在等待客户端接入,然后本地运行客户端
控制台输入你好,然后服务器端接收并显示你好
4.拓展
标签:
原文地址:http://www.cnblogs.com/feifeishi/p/5887900.html