socketserver多线程简单实现
客户端:
import java.io.BufferedReader; import java.io.IOException; import java.io.InputStream; import java.io.InputStreamReader; import java.io.OutputStream; import java.io.PrintWriter; import java.net.Socket; import java.net.UnknownHostException; public class socket { public static void main(String[] args) throws UnknownHostException, IOException { //。客户端先输出,再输入。服务端就先输入再输出。 Socket s=new Socket("127.0.0.1", 10004); InputStream inputstream = s.getInputStream(); OutputStream outputstream = s.getOutputStream(); PrintWriter printWriter=new PrintWriter(outputstream); printWriter.print("客户端发送信息:我是客户端"); printWriter.flush(); s.shutdownOutput();//关闭输出流 InputStreamReader inputStreamReader=new InputStreamReader(inputstream); BufferedReader bufferedReader=new BufferedReader(inputStreamReader); String info = bufferedReader.readLine(); System.out.println("接收服务器端数据:" + info); printWriter.close(); outputstream.close(); bufferedReader.close(); inputstream.close(); s.close(); } }
线程:
import java.io.BufferedReader; import java.io.IOException; import java.io.InputStream; import java.io.InputStreamReader; import java.io.OutputStream; import java.io.PrintWriter; import java.net.Socket; public class SocketThread extends Thread{ private Socket socket; public SocketThread(Socket socket) { this.socket = socket; } public void run() { try { //。得到一个输入流 InputStream inputStream = socket.getInputStream(); //。输入缓冲区只能使用字符流,上面的inputStream是字节流,这里做一个转换 InputStreamReader inputStreamReader = new InputStreamReader(inputStream); //。将字符流加入缓冲区 BufferedReader bufferedReader = new BufferedReader(inputStreamReader); //。读取客户端发送的数据,此处只读取一行。 String temp = bufferedReader.readLine(); System.out.println("接收客户端信息:" + temp); //。在这里停顿5秒,是为了看两个客户端同时连接的情况。这里是很简单的来一个客户端创建一个线程,任务结束就销毁线程。 try { sleep(5000); } catch (InterruptedException e) { // TODO Auto-generated catch block e.printStackTrace(); } //。输出流 OutputStream outputStream = socket.getOutputStream(); //。个人理解为输出流加入到输出缓冲区 PrintWriter printWriter = new PrintWriter(outputStream); //。输出流添加信息 printWriter.print("你好,服务端已接收到您的信息"); //。将输出流信息发送至客户端 printWriter.flush(); //。关闭指定socket的输出流 socket.shutdownOutput(); //。关闭相应的资源,输入输出缓冲区,输入输出流等 bufferedReader.close(); inputStream.close(); printWriter.close(); outputStream.close(); } catch (IOException e) { e.printStackTrace(); } } }
服务端:
import java.io.IOException; import java.net.ServerSocket; import java.net.Socket; public class socketserver { public static void main(String[] args) throws IOException { ServerSocket serverSocket = new ServerSocket(10004); System.out.println("服务端已启动,等待客户端连接.."); while (true) { //。循环监听socket Socket socket = serverSocket.accept();// 侦听并接受到此套接字的连接,返回一个Socket对象 //。监听一个socket就创建一个socketthread对象 SocketThread socketThread = new SocketThread(socket); //。此处调用start方法,不可直接调用run方法,直接调用run方法不创建线程。 socketThread.start(); } } }