java之网络编程(二)

CP(建立连接通道)编程的客户端的开发步骤
 1)创建客户端的Socket对象
  Socket:就是客户端的Socket
  构造方法
  public Socket(InetAddress address, int port)
  public Socket(String host, int port):创建客户端套接字对象,并且指定端口号和ip文本形式
 2)获取通道内的输出流对象
 3)给服务器端写数据 
 4)释放资源
 java.net.ConnectException: Connection refused: connect 连接被拒绝
 不要先运行客户端,客户端的连接需要服务器监听到才能连接

服务端的开发步骤:

  1)创建服务器端的Socket对象
  2)监听客户端的连接(阻塞方法)
  3)获取通道内的输入流
  4)读取数据,显示控制台

  5)释放资源

举例:

public class ClientDemo {
public static void main(String[] args) throws IOException, IOException {
	Socket s=new Socket("192.168.43.204",5555);
	//获取通道内的流
	OutputStream os = s.getOutputStream();
	os.write("你最牛逼的爸爸我来了".getBytes());
	s.close();
}
}
public class ServerDemo {
public static void main(String[] args) throws IOException {
	ServerSocket s=new ServerSocket(5555);
	//监听
	Socket s1 = s.accept();
	InputStream in = s1.getInputStream();
	//读数据显示在控制台上
	String ip = s.getInetAddress().getHostAddress();
    byte[] b=new byte[1024];
    int len = in.read(b);
    String ss=new String(b,0,len);
    System.out.println("from:"+ip+"data:"+ss);
    s.close();
}
}
客户端将文本文件中的数据,复制到服务器端输出的新的java文件中,然后服务器端要给客户端反馈数据,客户端将反馈的数据展示
举例:
public class ClientDemo {
public static void main(String[] args) throws IOException, IOException {
	Socket s=new Socket("192.168.43.204",5252);
	BufferedReader br=new BufferedReader(
			new FileReader("a.txt"));
	BufferedWriter bw=new BufferedWriter(
			new OutputStreamWriter(s.getOutputStream()));
	String line=null;
	while((line=br.readLine())!=null) {
	    bw.write(line);
	    bw.newLine();
	    bw.flush();
	}
	s.shutdownOutput();
	BufferedReader b=new BufferedReader(
			new InputStreamReader(s.getInputStream()));
	String readLine = b.readLine();
	System.out.println(readLine);
	s.close();
	
}
}

public class ServerDemo {
    public static void main(String[] args) throws  IOException {
    ServerSocket ss=new ServerSocket(5252);
    Socket s = ss.accept();
    BufferedReader br=new BufferedReader(
    		new InputStreamReader(s.getInputStream())); 
    BufferedWriter bw=new BufferedWriter(
    		new FileWriter("copy2.txt"));
    String line=null;
    while((line=br.readLine())!=null) {
    	bw.write(line);
    	bw.newLine();
    	bw.flush();
    }
    BufferedWriter b=new BufferedWriter(
    		new OutputStreamWriter(s.getOutputStream()));
    b.write("文件上传成功");
    b.newLine();
    b.close();
    s.close();
    } 
}

注释:加反馈的操作,用shutdownOutput方法,可以让客户端知道服务端接受数据结束,反馈收到文件了。

总结:客户端编写步骤:

          1.创建Socket对象,设置ip以及端口号

          2.发横装通道内的流

          3.创建一个空字符串

          4.while循环实行边读边写

          5.关闭Socket对象

          服务端编写步骤:

          1.创建Socket对象,设置端口号

          2.对客户端进行监听

          3.封装通道内的流

          4.创建空字符串

          5.while循环实行边读边写

          6.关闭对客户端的监听

猜你喜欢

转载自blog.csdn.net/wt5264/article/details/80681122