标签:
import java.io.PrintStream; import java.net.ServerSocket; import java.net.Socket; //================================================= // File Name : HelloServer_demo //------------------------------------------------------------------------------ // Author : Common //主类 //Function : HelloServer_demo public class HelloServer_demo { public static void main(String[] args) throws Exception{ // TODO 自动生成的方法存根 ServerSocket server = null; //声明ServerSocket对象 Socket client = null; //一个Socket对象表示一个客户端 PrintStream out = null; //声明打印流对象,以向客户端输出 server = new ServerSocket(8888); //表示服务器在8888端口上等待客户端的访问 System.out.println("服务器运行,等待客户端连接"); client = server.accept(); //程序阻塞,等待客户端连接 String str = "HelloWord"; //要向客户端输出信息 out = new PrintStream(client.getOutputStream()); //实例化打印流对象,输出信息 out.println(str); out.close(); client.close(); server.close(); } }
import java.io.BufferedReader; import java.io.InputStreamReader; import java.net.Socket; //================================================= // File Name : HelloClient_demo //------------------------------------------------------------------------------ // Author : Common //主类 //Function : HelloClient_demo public class HelloClient_demo { public static void main(String[] args) throws Exception{ // TODO 自动生成的方法存根 Socket client = null; //声明Socket对象 client = new Socket("localhost",8888); //指定连接的主机和端口 BufferedReader buf = null; //声明BufferedReader对象,接受信息 //指定客户端的输入流 buf = new BufferedReader(new InputStreamReader(client.getInputStream())); String str = buf.readLine(); System.out.println("服务器输出的内容是"+str); client.close(); buf.close(); } }
标签:
原文地址:http://www.cnblogs.com/tonglin0325/p/5323201.html