首先,创建一个服务器端的套接字,并规定套接字监听的端口:
ServerSocket serverSocket = new ServerSocket(8001);
然后,等待客户端通过端口8001的请求:
Socket socket=serverSocket.accept();接下来创建客户端接收到的套接字的输入输出流,并将输入输出流转化成扫描器和写入器:
InputStream inputStream = incomingSocket.getInputStream(); OutputStream outputStream = incomingSocket.getOutputStream(); //将输入流转化为扫描器,输出流转化为写入器 Scanner inScanner=new Scanner(inputStream); PrintWriter outPrintWriter= new PrintWriter(outputStream, true);接下来就可以运用扫描器获得客户端传来的数据,并运用写入器将传来的数据发送给客户端:
String backString=inScanner.next(); outPrintWriter.println("you give me:"+backString);
运用命令行的telnet命令就可以连接上客户端:
可以多次创建连接:
一下为完整代码:
<span style="font-size: 14px; font-family: Arial, Helvetica, sans-serif; background-color: rgb(255, 255, 255);"></span><pre name="code" class="java">package server; import java.io.IOException; import java.io.InputStream; import java.io.OutputStream; import java.io.PrintWriter; import java.net.ServerSocket; import java.net.Socket; import java.util.Scanner; public class ThreadEchoServer { public static void main(String[] args) { // TODO Auto-generated method stub try { int i=1; ServerSocket serverSocket = new ServerSocket(8001); while(true){ //等待客户端通过端口8001请求的连接 Socket socket=serverSocket.accept(); System.out.println("spawning"+i); Runnable runnable= new ThreadEchoHandler(socket); Thread thread = new Thread(runnable); thread.start(); i++; } } catch (IOException e) { // TODO Auto-generated catch block e.printStackTrace(); } } } class ThreadEchoHandler implements Runnable { private Socket incomingSocket; public ThreadEchoHandler(Socket in){ incomingSocket=in; } public void run(){ try { try { //建立套接字的输入输出流 InputStream inputStream = incomingSocket.getInputStream(); OutputStream outputStream = incomingSocket.getOutputStream(); //将输入流转化为扫描器,输出流转化为写入器 Scanner inScanner=new Scanner(inputStream); PrintWriter outPrintWriter= new PrintWriter(outputStream, true); //运用写入器的println函数向客户端输出字符串 outPrintWriter.println("welcome!"); //将客户端传输的数据发送回去,如果客户端输入的数据为bye,则断开连接 boolean flag=false; while(!flag&&inScanner.hasNext()){ String backString=inScanner.next(); outPrintWriter.println("you give me:"+backString); if(backString.trim().equals("bye")){ flag=true; } } } finally { // TODO: handle exception //关闭套接字(很重要,防止造成资源浪费) incomingSocket.close(); } } catch (IOException e) { // TODO: handle exception } } }
<span style="font-size: 14px; font-family: Arial, Helvetica, sans-serif; background-color: rgb(255, 255, 255);">本文参考《Java核心技术卷II》</span>