1. 程式人生 > >Java——socket實現tcp連線

Java——socket實現tcp連線

Server:

import java.io.IOException;
import java.net.ServerSocket;
import java.net.Socket;
 
public class Server {
 
    /**
     * Socket服務端
     */
    public static void main(String[] args) {
        try {
            ServerSocket serverSocket = new ServerSocket(8888);
            System.out.println(
"服務端已啟動,等待客戶端連線.."); while (true) { Socket socket = serverSocket.accept();// 偵聽並接受到此套接字的連線,返回一個Socket物件 SocketThread socketThread = new SocketThread(socket); socketThread.start(); } } catch (IOException e) { e.printStackTrace(); } } }

Client:

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 Client {
 
    /**
     * Socket客戶端
     
*/ public static void main(String[] args) { try { //建立Socket物件 Socket socket=new Socket("localhost",8888); //根據輸入輸出流和服務端連線 OutputStream outputStream=socket.getOutputStream();//獲取一個輸出流,向服務端傳送資訊 PrintWriter printWriter=new PrintWriter(outputStream);//將輸出流包裝成列印流 printWriter.print("服務端你好,我是客戶1"); printWriter.flush(); socket.shutdownOutput();//關閉輸出流 InputStream inputStream=socket.getInputStream();//獲取一個輸入流,接收服務端的資訊 InputStreamReader inputStreamReader=new InputStreamReader(inputStream);//包裝成字元流,提高效率 BufferedReader bufferedReader=new BufferedReader(inputStreamReader);//緩衝區 String info=""; String temp=null;//臨時變數 while((temp=bufferedReader.readLine())!=null){ info+=temp; System.out.println("客戶端接收服務端傳送資訊:"+info); } //關閉相對應的資源 bufferedReader.close(); inputStream.close(); printWriter.close(); outputStream.close(); socket.close(); } catch (UnknownHostException e) { e.printStackTrace(); } catch (IOException e) { e.printStackTrace(); } } }