gistfile1.txt import java.io.DataInputStream;import java.io.DataOutputStream;import java.io.IOException;import java.net.ServerSocket;import java.net.Socket;/** * 服务器端Socket * @author YJ */public class Server {private ServerSocket se
import java.io.DataInputStream; import java.io.DataOutputStream; import java.io.IOException; import java.net.ServerSocket; import java.net.Socket; /** * 服务器端Socket * @author YJ */ public class Server { private ServerSocket serverSocket; public Server(){ try { serverSocket = new ServerSocket(8000); //创建服务器Socket System.out.println("a server started..."); while(true){ Socket connectToClient = serverSocket.accept(); //启动客户端监听 new ServerThread(connectToClient).start(); //客户端连接之后 启动新线程 } } catch (IOException e) { e.printStackTrace(); } } class ServerThread extends Thread{ //内部线程类 private DataInputStream isFromClient; private DataOutputStream osToClient; public ServerThread(Socket connectToClient){ System.out.print("a client connected: "); System.out.println(connectToClient.getRemoteSocketAddress()); try { isFromClient = new DataInputStream(connectToClient.getInputStream()); osToClient = new DataOutputStream(connectToClient.getOutputStream()); } catch (IOException e) { e.printStackTrace(); } } public void run() { while(true){ //可多长输入输出 try { int i = isFromClient.readInt(); //读入客户端传入值 osToClient.writeInt(i*i); //返回值的平方 } catch (IOException e) { System.out.println("a client closed..."); break; } } } } public static void main(String[] args) { new Server(); } }