今天心血来潮写了一个Socket的小Demo,以此记录。
创建一个Project
创建一个包:com.xier.scoket
创建一个类Client 代码如下:此类在Socket中充当着客户端的角色
publci class Client(){
public static void main(String[] args) throws Exception {
// 创建网络连接
Socket client = new Socket("localhost", 6666);
// 创建 需要使用到的流
InputStream is = null;
BufferedReader reader = null;
is = client.getInputStream();
//通过流,读取需要的文件
reader = new BufferedReader(new InputStreamReader(is));
// IO操作
String msg = reader.readLine();
System.out.println("Server: " + msg);
// 关闭资源
reader.close();
client.close();
}
}
然后在创建一个Server:此类在Socket中扮演着服务器的角色
public class Server(){
public static void main(String[] args)throws Exception {
//代开网络连接
ServerSocket server=new ServerSocket(6666);
//打开IO操作流
OutputStream out=null;
PrintStream pw=null;
System.out.println("服务器已经准备好,等待客户端的连接 ");
//得到连接对象
Socket client=server.accept();
//获取客户端访问的Ip
System.out.println("客户端IP是:"+client.getLocalAddress().getHostAddress());
out=client.getOutputStream();
pw=new PrintStream(out);
//传递需要的信息
String msg="你不坚强,没人替你勇敢";
pw.print(msg);
//关闭资源
client.close();
server.close();
}
}
在测试时,先跑Server 然后再跑Client
出现一下效果: