这样的好处就是不用规定服务器,和客户端发送接收的顺序。谁先发送数据,谁阻塞接收后,再发送。可以同时发送同时接收
服务器:
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.net.ServerSocket;
import java.net.Socket;
import java.nio.charset.StandardCharsets;
import java.util.Scanner;
public class Server1 {
public static void main(String[] args) throws IOException {
ServerSocket ss = new ServerSocket(3000);
Socket sc=ss.accept();
Rd rd=new Rd(sc);
Wr wr=new Wr(sc);
rd.start();
wr.start();
}
}
class Rd extends Thread{
Socket sc;
Rd(Socket sc){
this.sc=sc;
}
public synchronized void run(){
while(true) {
try {
InputStream is = sc.getInputStream();
int t = is.read();
String sin = "";
while (((char) t != '^') && (t != -1)) {
sin = sin + (char) t;
t = is.read();
}
System.out.println(sin);
} catch (IOException e) {
throw new RuntimeException(e);
}
}
}
}
class Wr extends Thread{
Socket sc;
Wr(Socket sc){
this.sc=sc;
}
public synchronized void run(){
while(true) {
try {
OutputStream os = sc.getOutputStream();
// os.write("S^".getBytes(StandardCharsets.UTF_8));
Scanner scanner = new Scanner(System.in);
String s = scanner.nextLine();
os.write((s + '^').getBytes(StandardCharsets.UTF_8));
} catch (IOException e) {
throw new RuntimeException(e);
}
}
}
}
客户端:
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.net.ServerSocket;
import java.net.Socket;
import java.nio.charset.StandardCharsets;
import java.util.Scanner;
public class Client1 {
public static void main(String[] args) throws IOException {
Socket sc=new Socket("127.0.0.1",3000);
Rd1 rd1=new Rd1(sc);
Wr1 wr1=new Wr1(sc);
rd1.start();
wr1.start();
}
}
class Rd1 extends Thread{
Socket sc;
Rd1(Socket sc){
this.sc=sc;
}
public synchronized void run(){
while(true) {
try {
InputStream is = sc.getInputStream();
int t = is.read();
String sin = "";
while (((char) t != '^') && (t != -1)) {
sin = sin + (char) t;
t = is.read();
}
System.out.println(sin);
} catch (IOException e) {
throw new RuntimeException(e);
}
}
}
}
class Wr1 extends Thread{
Socket sc;
Wr1(Socket sc){
this.sc=sc;
}
public synchronized void run(){
while(true) {
try {
OutputStream os = sc.getOutputStream();
// os.write("c^".getBytes(StandardCharsets.UTF_8));
Scanner scanner = new Scanner(System.in);
String s = scanner.nextLine();
os.write((s + '^').getBytes(StandardCharsets.UTF_8));
} catch (IOException e) {
throw new RuntimeException(e);
}
}
}
}