最近需要做一个微信小程序,有发卷和收卷的功能。要实现一个聊天室,将所有的小程序链接起来,做到统一收发试卷,所以研究了一下socket。
1.tcp版
代码
public class Server {
public static void main(String[] args) throws IOException {
//1.创建ServerSocket 并制定监听端口
int port = 8888;
ServerSocket serverSocket = new ServerSocket(port);
//2.创建Socket,存储监听到的链接
Socket socket = new Socket();
System.out.println("*******服务器已经启动了,开始监听8888端口********");
int count = 0;
while(true){
socket = serverSocket.accept(); //程序会进入到阻塞状态,直到接收到客户端发送的socket
count ++;
System.out.println("服务端:监听到第"+count+"个socket");
//将接受到的socket扔到另一个线程里去处理,然后继续监听
ServerThread thread = new ServerThread(socket);
thread.start();
}
}
}
public class ServerThread extends Thread {
private Socket socket = null;
public ServerThread(Socket socket){
this.socket = socket;
}
@Override
public void run() {
try {
//获取客户算发送的字节流数据
InputStream is = socket.getInputStream();
//获取字符流数据
InputStreamReader isr = new InputStreamReader(is);
//创建缓存
BufferedReader br = new BufferedReader(isr);
//打印客户端发送的数据
String info = null;
while((info = br.readLine())!=null){
System.out.println(info);
}
socket.shutdownInput();
br.close();
isr.close();
is.close();
socket.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
public class Client {
public static void main(String[] args) throws IOException {
//指定访问的主机
InetAddress address = InetAddress.getByName(“localhost”);
int port = 8888;
Socket socket = new Socket(address, port);
OutputStream os = socket.getOutputStream();
PrintWriter pw = new PrintWriter(os);
pw.write("我是客户端:用户名:123,密码:123");
pw.flush();
pw.close();
os.close();
socket.close();
}
}