网路编程的实例

 
package com.itcast.demo01.TCP;

import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.net.ServerSocket;
import java.net.Socket;

/**
* @author newcityman
* @date 2019/7/30 - 22:57
* TCP通信的服务器端:接受客户端的请求,读取客户端发送的数据 ,给客户端回写数据
* 表示服务器的类:
* java.net.serverSocket
*
* 服务器的实现步骤
* 1、创建服务器ServerSocket对象和系统要指定的端口号
* 2、使用ServerSocket对象中的accept方法,获取到请求的客户端对象Socket
* 3、使用Socket对象中的方法getInputStream()获取网络字节流InputStream对象
* 4、使用网络字节输入流InputStream对象中的方法read,读取客户端发送的数据
* 5、使用Socket对象中的方法getOutputStream()获取网络字节输出流OutputStream对象
* 6、使用网路字节输出流OutputStream对象中的方法write,给客户端会写数据
* 7、释放资源
*
*/
public class TCPServer {
public static void main(String[] args) throws IOException {
ServerSocket server= new ServerSocket(8888);
Socket socket = server.accept();
InputStream is= socket.getInputStream();
byte[] bytes = new byte[1024];
int len = is.read(bytes);
System.out.println(new String(bytes,0,len));
OutputStream os = socket.getOutputStream();
os.write("收到谢谢".getBytes());
socket.close();
os.close();
}

}


package com.itcast.demo01.TCP;

import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.net.Socket;

/**
* @author newcityman
* @date 2019/7/30 - 22:41
* 要求:
* 实现客户端和服务器端之间的数据交互
* 实现步骤:
* 1、创建一个客户端对象Socket,构造方法绑定服务器的ip地址和端口号
* 2、使用Socket对象中的方法getOutputStream()获取网络字节输出流OutputStream对象
* 3、使用网络字节输出流OutputStream对象中的方法write,给服务器发送数据
* 4、使用Socket对象中的方法getInputStream()获取网络字节输入流InputStream对象
* 5、使用网络字节输入流InputStream对象中的方法read,接受服务器发送过来的数据
* 6、释放资源
*
* 注意:
* 1、客户端和服务器端进行交互,必须使用Socket中提供的网络流,不能使用自己创建的流
* 2、当我们创建客户端对象Socket的时候,就会去请求服务器和服务器进行3次握手建立连接通路
* 此时如果服务器没有启动,则会抛出异常
* 如果服务器已经启动,就可以进行正常的数据交互
*/
public class TCPClient {
public static void main(String[] args) throws IOException {
Socket socket = new Socket("127.0.0.1",8888);
OutputStream out = socket.getOutputStream();
out.write("建军节快乐".getBytes());
InputStream inputStream = socket.getInputStream();
byte[] bytes = new byte[1024];
int len = inputStream.read(bytes);
System.out.println(new String(bytes,0,len));
socket.close();

}
}
 

猜你喜欢

转载自www.cnblogs.com/newcityboy/p/11273551.html