Java Socket 实现服务器与客户端通讯
Java Socket 实现服务器与客户端的互相发送消息互不干扰,即无需接收到信息后才可以发送信息。做到了接收信息和发送信息分离。
服务器创建了两个Socket分别用来输入输出
import java.io.*;
import java.net.ServerSocket;
import java.net.Socket;
import java.nio.charset.StandardCharsets;
import java.util.Scanner;
public class Server {
public static void main(String[] args) throws IOException {
ServerSocket ss = new ServerSocket(6666); // 监听指定端口
System.out.println("服务器正在启动......");
for (;;) {
Socket sock = ss.accept();
System.out.println("连接上客户端 " + sock.getRemoteSocketAddress());
Thread writeThread = new writeThread(sock);
writeThread.start();
Thread readThread = new readThread(sock);
readThread.start();
}
}
}
class writeThread extends Thread {
Socket sock;
public writeThread(Socket sock) {
this.sock = sock;
}
@Override
public void run() {
BufferedWriter bw = null;
try {
bw = new BufferedWriter(new OutputStreamWriter(sock.getOutputStream(), StandardCharsets.UTF_8));
Scanner sc = new Scanner(System.in);
while(true){
try{
bw.write("server:"+sc.next()+"\n");
bw.flush();
} catch (IOException e) {
e.printStackTrace();
}
}
} catch (IOException e1) {
// TODO Auto-generated catch block
e1.printStackTrace();
}finally {
try {
bw.close();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
}
class readThread extends Thread {
Socket sock;
public readThread(Socket sock) {
this.sock = sock;
}
@Override
public void run() {
BufferedReader br = null;
try {
br = new BufferedReader(new InputStreamReader(sock.getInputStream(), StandardCharsets.UTF_8));
while(true){
try {
String msg = br.readLine();
System.out.println(msg);
} catch (IOException e) {
e.printStackTrace();
}
}
} catch (IOException e1) {
// TODO Auto-generated catch block
e1.printStackTrace();
}finally {
try {
br.close();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
}
客户端可以创建多个来连接服务器
import java.io.*;
import java.net.Socket;
import java.nio.charset.StandardCharsets;
import java.util.Scanner;
public class more_client {
public static void main(String[] args) throws IOException{
try {
Socket sock = new Socket("localhost", 6666); // 连接指定服务器和端口
System.out.println("连接成功,可以开始通话了");
//构建IO
InputStream is = sock.getInputStream();
OutputStream os = sock.getOutputStream();
BufferedWriter bw = new BufferedWriter(new OutputStreamWriter(os, StandardCharsets.UTF_8));
BufferedReader br = new BufferedReader(new InputStreamReader(is, StandardCharsets.UTF_8));
Scanner sc = new Scanner(System.in);
Thread readThread = new Thread(){
public void run(){
while(true){
String msg = null;
try {
msg = br.readLine();
} catch (IOException e) {
e.printStackTrace();
}
System.out.println(msg);
}
}
};
Thread writeThread = new Thread(){
public void run(){
while(true){
try {
bw.write("clien:"+sc.next()+"\n");
bw.flush();
} catch (IOException e) {
e.printStackTrace();
}
}
}
};
readThread.start();
writeThread.start();
} catch (Exception e) {
e.printStackTrace();
}
}
}