java网络编程
网络通信要素
IP
和端口号InetAddress
InetSocketAddress
- 网络通信协议
Socket通信 [TCP]
//Client端
public class Client {
public static void main(String[] args) throws Exception {
//获取服务器地址,端口号
InetAddress ip = InetAddress.getByName("127.0.0.1");
int port = 888;
//建立连接
Socket socket = new Socket(ip, port);
//发送数据
OutputStream out=socket.getOutputStream(); //将数据写入流
out.write("你好,服务器888".getBytes());
out.close(); //记得关闭流
socket.close();
}
}
//Server端
public class Server {
public static void main(String[] args) throws Exception {
Socket socket=null;
//创建本机端口
ServerSocket serverSocket = new ServerSocket(888);
//监听消息
socket=serverSocket.accept();
//获取数据
InputStream in = socket.getInputStream();
//用一个管道来接收流
ByteArrayOutputStream os = new ByteArrayOutputStream();
int data=0;
while ((data = in.read()) != -1) {
os.write(data); //将socket流中获取的数据放入管道
}
System.out.println(os.toString()); //输出管道中的数据
os.close();
in.close();
socket.close();
serverSocket.close();
}
}
初识tomcat
服务器:
- 自定义S
- 用别人写好的服务器 S,比如tomcat
客户端:
- 自己手写 C
- 浏览器 B