1. 程式人生 > >通過TCP進行通信

通過TCP進行通信

pri tin line block amr 通過 new known out

public class Server {
    public static void main(String[] args) {
        try {
            ServerSocket serverSocket =  new ServerSocket(8888);
            System.out.println("服務器即將啟動,等待客戶端的連接");
            Socket socket = serverSocket.accept();
            InputStream is = socket.getInputStream();
            InputStreamReader isr 
= new InputStreamReader(is); BufferedReader br = new BufferedReader(isr); String info = null; while ((info=br.readLine())!=null) { System.out.println("我是服務器,客戶端說" + info); } br.close(); isr.close(); is.close(); socket.close(); serverSocket.close(); }
catch (IOException e) { // TODO Auto-generated catch block e.printStackTrace(); } } }
public class Client {
    public static void main(String[] args) {
        try {
            Socket socket = new Socket("localhost",8888);
            OutputStream os 
= socket.getOutputStream(); PrintWriter pw = new PrintWriter(os); pw.write("用戶名:admin;密碼:123"); pw.flush(); socket.shutdownOutput(); pw.close(); os.close(); socket.close(); } catch (UnknownHostException e) { // TODO Auto-generated catch block e.printStackTrace(); } catch (IOException e) { // TODO Auto-generated catch block e.printStackTrace(); } } }

通過TCP進行通信