线程实现ServerSocket和Socket实现数据交互

时间:2021-09-13 22:39:08

定义一个MyServer类

import java.io.IOException;
import java.net.ServerSocket;

public class MyServer {
public static void main(String[] args) {
try {
System.out.println("服务器启动");
ServerSocket ss = new ServerSocket(80);
while (true) {
new MyThread(ss.accept()).start();//监听到一次 开启一个线程,省去很多资源,这里很多人都会用死循环去实现循环监听,很浪费资源。

}

} catch (IOException e) {
e.printStackTrace();
}
}
}

-----------------------------------

客户端访问服务器端的类

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.OutputStreamWriter;
import java.io.PrintWriter;
import java.net.Socket;
import java.util.Scanner;

public class MyClient {
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
try {
System.out.println("客户端启动");
Socket socket = new Socket("127.0.0.1", 80);//访问本机,端口80
PrintWriter out = new PrintWriter(new OutputStreamWriter(
socket.getOutputStream()));//创建一个输出流,手动输入要转换的字符串
out.println(sc.next());
out.flush();
BufferedReader in = new BufferedReader(new InputStreamReader(
socket.getInputStream()));//创建一个输入流,接受服务器返回的数据
String sline = in.readLine();
System.out.println("从服务器端返回的数据是:" + sline);
} catch (IOException e) {
e.printStackTrace();
}

}
}

---------------------------------------------

线程类具体实现数据交互

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.OutputStreamWriter;
import java.io.PrintWriter;
import java.net.Socket;

public class MyThread extends Thread {

Socket socket;

public MyThread(Socket socket) {
this.socket = socket;
}

@Override
public void run() {
try {
BufferedReader in = new BufferedReader(new InputStreamReader(
socket.getInputStream()));
String sline = in.readLine();
System.out.println("从客户端接受的数据是:" + sline);
PrintWriter pw = new PrintWriter(new OutputStreamWriter(
socket.getOutputStream()));
pw.println((sline==null)?"":sline.toUpperCase());
pw.flush();
System.out.println("服务器结束");

} catch (IOException e) {
e.printStackTrace();
}
}

}