JAVA 学习(3,黑马 Java 全套百度云
发布于: 3 小时前
Socket socket =null;
OutputStream os = null;
try {
InetAddress ServerIP =InetAddress.getByName("127.0.0.1");
int port = 9999;
socket = new Socket(ServerIP,port);
os = socket.getOutputStream();
os.write("hello , welcome to learn the Java".getBytes());
} catch (Exception e) {
e.printStackTrace();
}finally {
if(os!=null){
try {
os.close();
} catch (IOException e) {
e.printStackTrace();
}
}
if(socket!=null){
try {
socket.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
}
复制代码
}
服务器
1. 建立服务的端口 ServerSocket
2. 等待用户的连接 accept
3. 接收用户消息
复制代码
package com.myweb;
import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.net.ServerSocket;
import java.net.Socket;
public class TcpServer {
public static void main(String[] args) {
ServerSocket serverSocket =null;
Socket socket = null;
InputStream is = null;
ByteArrayOutputStream baos = null;
try {
serverSocket = new ServerSocket(9999);
socket = serverSocket.accept();
is = socket.getInputStream();
//管道流
baos = new ByteArrayOutputStream();
byte[] buffer = new byte[1024];
int len;
while ((len= is.read(buffer))!=-1){
baos.write(buffer,0,len);
}
System.out.println(baos.toString());
} catch (IOException e) {
e.printStackTrace();
}finally {
//关闭资源
if(baos!=null){
try {
baos.close();
} catch (IOException e) {
e.printStackTrace();
}
}
if(is!= null){
try {
is.close();
} catch (IOException e) {
e.printStackTrace();
}
}
if(socket!=null){
try {
socket.close();
} catch (IOException e) {
e.printStackTrace();
}
}
if(serverSocket!=null){
try {
serverSocket.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
}
复制代码
}
[](https://gitee.com/vip204888/java-p7)Tomcat
=====================================================================
服务器:Tomcat 服务器 S
客户端: 浏览器 B
[](https://gitee.com/vip204888/java-p7)UDP
### 最后
> **笔者已经把面试题和答案整理成了面试专题文档,有想获取到借鉴参考的朋友:点赞关注后,[戳这里即可免费领取](https://gitee.com/vip204888/java-p7)**
![image](https://static001.geekbang.org/infoq/b6/b63e41fba16a4fd8e1c42032a2b07f19.png)
?![image](https://static001.geekbang.org/infoq/c9/c9ca5660c211e369386104b6f6347e0a.png)
![image](https://static001.geekbang.org/infoq/db/dbe7bdaf15f53caac61273a0e8995feb.png)
?![image](https://static001.geekbang.org/infoq/28/286282dc92ad943f5e27713cad095608.png)
![image](https://static001.geekbang.org/infoq/9e/9ef75ae3acc11cbb2044b3b07061f7a5.png)
?![image](https://static001.geekbang.org/infoq/24/242e6817a29e2ac31646c41e0701143b.png)
复制代码
划线
评论
复制
发布于: 3 小时前阅读数: 4
程序猿一枚
关注
VX:vip204888 领取资料 2021.07.29 加入
还未添加个人简介
评论