Java和大数据系列
注:大家觉得博客好的话,别忘了点赞收藏呀,本人每周都会更新关于人工智能和大数据相关的内容,内容多为原创,Python Java Scala SQL 代码,CV NLP 推荐系统等,Spark Flink Kafka Hbase Hive Flume等等~写的都是纯干货,各种顶会的论文解读,一起进步。
今天和大家分享一下Java 多线程socket 网络协议传输的代码
#博学谷IT学习技术支持#
前言
大数据框架很多底层都用到了Java多线程socket网络协议传输,今天来分享一段代码实战。
一、Socket是什么?
Socket是应用层与TCP/IP协议族通信的中间软件抽象层,它是一组接口。在设计模式中,Socket其实就是一个门面模式,它把复杂的TCP/IP协议族隐藏在Socket接口后面,对用户来说,一组简单的接口就是全部,让Socket去组织数据,以符合指定的协议。
你会使用它们吗?
二、使用步骤
1.定义发送线程
由于使用多线层模式,所以首先实现2个Runnable接口,一个用来发送,一个用来接受
代码如下(示例):
package pack03;
import java.io.IOException;
import java.io.OutputStream;
import java.net.Socket;
import java.util.Scanner;
public class MyRunnable01Send implements Runnable{
private Socket socket = null;
public MyRunnable01Send() {
}
public MyRunnable01Send(Socket socket) {
this.socket = socket;
}
@Override
public void run() {
try {
OutputStream outputStream = socket.getOutputStream();
Scanner scanner = new Scanner(System.in);
while (true){
String line = scanner.nextLine();
outputStream.write(line.getBytes());
if ("exit".equals(line)){
break;
}
System.out.println();
}
socket.close();
} catch (IOException e) {
throw new RuntimeException(e);
}
}
}
2.定义接受线程
代码如下(示例):
package pack03;
import java.io.IOException;
import java.io.InputStream;
import java.net.Socket;
public class MyRunnable02Receive implements Runnable{
private Socket socket = null;
public MyRunnable02Receive() {
}
public MyRunnable02Receive(Socket socket) {
this.socket = socket;
}
@Override
public void run() {
try {
InputStream inputStream = socket.getInputStream();
byte[] bytes = new byte[1024];
while (true){
int len = inputStream.read(bytes);
String str = new String(bytes, 0, len);
if ("exit".equals(str)){
break;
}
System.out.println(str);
}
inputStream.close();
} catch (IOException e) {
throw new RuntimeException(e);
}
}
}
3.定义服务器Server
代码如下(示例):
package pack03;
import java.io.IOException;
import java.net.ServerSocket;
import java.net.Socket;
public class Server {
public static void main(String[] args) throws IOException {
ServerSocket serverSocket = new ServerSocket(10010);
Socket socket = serverSocket.accept();
MyRunnable01Send sendRunnable = new MyRunnable01Send(socket);
Thread sendThread = new Thread(sendRunnable, "发送线程");
sendThread.start();
MyRunnable02Receive receiveRunnable = new MyRunnable02Receive(socket);
Thread receiveThread = new Thread(receiveRunnable, "接受线程");
receiveThread.start();
}
}
4.定义客户端Client
代码如下(示例):
package pack03;
import java.io.IOException;
import java.net.Socket;
public class Client {
public static void main(String[] args) throws IOException {
Socket socket = new Socket("localhost",10010);
MyRunnable01Send sendRunnable = new MyRunnable01Send(socket);
Thread sendThread = new Thread(sendRunnable, "发送线程");
sendThread.start();
MyRunnable02Receive receiveRunnable = new MyRunnable02Receive(socket);
Thread receiveThread = new Thread(receiveRunnable, "接受线程");
receiveThread.start();
}
}
总结
本文通过Java多线程,来实现socket网络协议传输,非常简单的小案例。