tcp实现网络通信的两个例子
tcp实现客户端与服务端消息通信
客户端代码
public class TestClient {
public static void main(String[] args) {
InetAddress address;
Socket socket = null;
OutputStream os = null;
try {
// 获取服务器主机地址和端口号
address = InetAddress.getByName("localhost");
int port = 9999;
// 创建客户端
socket = new Socket(address, port);
// 向服务端发送数据
os = socket.getOutputStream();
os.write("你看什么?".getBytes());
} catch (Exception e) {
e.printStackTrace();
} finally {
try {
if (os!=null) {
os.close();
}
if (socket!=null) {
socket.close();
}
} catch (Exception e) {
e.printStackTrace();
}
}
}
}
服务端代码
/**
* 服务端
*/
public class TestServe {
public static void main(String[] args) {
ServerSocket serve = null;
Socket socket = null;
InputStream is= null;
ByteArrayOutputStream bos = null;
try {
// 创建服务端
serve = new ServerSocket(9999);
// 接受客户端
socket = serve.accept();
// 读取客户端数据
is = socket.getInputStream();
bos = new ByteArrayOutputStream();
byte [] buffer = new byte[1024];
int len;
while ((len = is.read(buffer))!=-1){
bos.write(buffer,0,len);
}
System.out.println(bos.toString());
} catch (Exception e) {
e.printStackTrace();
} finally {
try {
if (bos!=null) {
bos.close();
}
if (is!=null) {
is.close();
}
if (socket!=null) {
socket.close();
}
if (serve!=null) {
serve.close();
}
} catch (IOException e) {
e.printStackTrace();
}
}
}
}
tcp实现客户端上传文件到服务端功能
客户端
/**
* 模仿客户端与服务端之间的通信
* 进行文件上传
* 客户端
*/
public class TestClient2 {
public static void main(String[] args) throws Exception {
// 创建客户端
Socket socket = new Socket(InetAddress.getByName("localhost"), 9999);
OutputStream os = socket.getOutputStream();
//创建文件输入流
FileInputStream is = new FileInputStream(new File("Snipaste_2021-08-15_17-05-05.png"));
// 上传文件到服务端
uploadFile(os,is);
// 本次通信完成
socket.shutdownOutput();
// 获取服务端返回的数据
ByteArrayOutputStream bos = new ByteArrayOutputStream();
InputStream stream = socket.getInputStream();
uploadFile(bos,stream);
System.out.println(bos.toString());
stream.close();
bos.close();
is.close();
os.close();
socket.close();
}
private static void uploadFile(OutputStream os, InputStream is) throws Exception {
byte [] buffer = new byte[1024];
int len;
while ((len= is.read(buffer))!=-1){
os.write(buffer,0,len);
}
}
}
服务端
/**
* 服务端
*/
public class TestServe2 {
public static void main(String[] args) throws Exception {
// 创建服务端
ServerSocket server = new ServerSocket(9999);
// 接受客户端数据
Socket socket = server.accept();
InputStream is = socket.getInputStream();
FileOutputStream os = new FileOutputStream(new File("1.jpg"));
String result = acceptFile(is,os);
// 接收完成
socket.shutdownInput();
// 返回数据到客户端
socket.getOutputStream().write(result.getBytes());
socket.shutdownOutput();
os.close();
is.close();
socket.close();
server.close();
}
private static String acceptFile(InputStream is, FileOutputStream os) throws Exception {
byte [] buffer = new byte[1024];
int len;
while ((len= is.read(buffer))!=-1){
os.write(buffer,0,len);
}
return "上传完成";
}
}
版权声明:本文为weixin_43870670原创文章,遵循CC 4.0 BY-SA版权协议,转载请附上原文出处链接和本声明。