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)**

?

?

?
复制代码
划线
评论
复制
发布于: 3 小时前阅读数: 4
程序猿一枚
关注
VX:vip204888 领取资料 2021.07.29 加入
还未添加个人简介
评论