Socket實現簡單聊天

服務端:java

package main.java.com.socket_dome;

import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.net.ServerSocket;
import java.net.Socket;
import java.util.Scanner;

public class LoginServer {

    public static void main(String[] args) {
        Scanner input = new Scanner(System.in);
        ServerSocket serverSocket = null;
        Socket socket = null;
       
        try {
            //輸入提示語,表明服務端成功啓動
            System.out.println("啓動成功!");
            //創建客戶端,並鏈接8080端口號
            serverSocket = new ServerSocket(8080);
            //監聽客戶端
            socket = serverSocket.accept();
            //打開socket的I/O流
            InputStream is = socket.getInputStream();
            OutputStream os = socket.getOutputStream();
            //循環,讓服務端一直處於監聽狀態
            while(true){
                //接收來自客戶端的信息,而且打印在控制檯
                int len = 0;
                byte[] b = new byte[1024];
                len = is.read(b);
                System.out.println("客戶端說:"+ new String(b,0,len));
                System.out.println("服務端輸入:");
                //把回覆的內容打散成字節數組發送給客戶端
                String reply = input.next();
                os.write(reply.getBytes());
            }

        } catch (IOException e) {
            e.printStackTrace();
        }finally {
            try {
                //關閉socked,切記不能夠關閉i/o流
                socket.close();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }

    }
}
View Code

客戶端:sql

package main.java.com.socket_dome;

import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.net.ServerSocket;
import java.net.Socket;
import java.sql.SQLOutput;
import java.util.Scanner;

public class Clinet {

    public static void main(String[] args) {
        Scanner input = new Scanner(System.in);
        Socket socket = null;
        OutputStream os = null;
        InputStream is = null;

        try {
            //創建客戶端,本機鏈接測試
            socket = new Socket("localhost",8080);
            //打開輸出流
            os = socket.getOutputStream();
            is = socket.getInputStream();
            //不斷的來回交互,所以寫個死循環
            while (true){
                //發送信息給客戶
                System.out.println("客戶端輸入:");
                os.write(input.next().getBytes());
                //接收讀取的信息
                int len = 0 ;
                byte[] b = new byte[1024];
                len = is.read(b);
                System.out.println("服務器說:"+ new String(b,0,len));

            }
        } catch (IOException e) {
            e.printStackTrace();
        }finally {
             try {
                    //關閉socket
                    if (socket != null) {
                        socket.close();
                    }
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        }

}
View Code

效果:數組

 

 

相關文章
相關標籤/搜索