java socket點對點以及點對面編程實例

和socket編程有關的幾個類:
InetAddress
Socket:用在客戶端
ServerSocket:用在服務器端
一。點對點通信
服務器端:
package server;


import java.io.*;
import java.net.*;

public class Server {
private int port;
public Server(int port){
    this.port=port;
    start();
}
//將從客戶端收到的信息轉化爲大寫的
public String process(String line){
    return line.toUpperCase();
}
public void start(){
    try{
        //根據端口創建套接字
        ServerSocket myscoket=new ServerSocket(port);
        //顯示連接信息
        System.out.println("服務器啓動完成,監聽端口在"+port);
        System.out.println("正在等待客戶連接.........");
        //掛起等待客戶的請求
        Socket connection=myscoket.accept();
                //測試
                System.out.println("客戶發來連接請求.........");
        //獲取讀取客戶端的數據流
        BufferedReader in=new BufferedReader(new InputStreamReader(connection.getInputStream()));
        //獲取寫往客戶端的數據輸出流,true表示自動刷新
        PrintWriter out=new PrintWriter(connection.getOutputStream(),true);
        //向客戶發送歡迎的信息
        out.println("您好,服務器連接成功!");
        out.println("輸入bye斷開與服務器的連接");
        boolean done=false;
        while(!done){
            //讀取客戶端的內容
            String line=in.readLine();
            if(line==null){
                done=true;
            }else{
                //從服務器端顯示客戶端發送的信息
                System.out.println("從客戶端來的內容"+line);
                //信息處理
                String message=process(line);
                //向客戶端發送信息
                out.println("從服務器端口發送的信息"+message);
                if(line.trim().equals("BYE"))
                    done=true;
            }
        }
        //關閉通信
        connection.close();
    }catch(Exception e){
        System.out.println(e);
    }   
}
}

package server;

public class ServerDemo {

    /**
     * @param args
     */
    public static void main(String[] args) {
        // TODO Auto-generated method stub
if(args.length!=1){
    System.out.println("運行方式:java Server <端口號>");
    return;
}
try{
    //獲得端口號
    int port=Integer.parseInt(args[0]);
    Server myserver=new Server(port);
}catch(Exception e){
    System.out.println(e);
}
    }

}

客戶端:
package client;
import java.io.*;
import java.net.*;
public class Client {
private String host;
private int port;
public Client(String host,int port){
    this.host=host;
    this.port=port;
    connect();   
}
public void connect(){
    try{
        Socket connection;
        if(host.equals("localhost"))
        {connection=new Socket(InetAddress.getLocalHost(),port);}
        else
          { connection=new Socket(InetAddress.getByName(host),port);}   
        //獲得從鍵盤輸入流
        BufferedReader stdin=new BufferedReader(new InputStreamReader(System.in));
        //獲得服務器寫內容的數據流
        PrintWriter out=new PrintWriter(connection.getOutputStream(),true);
        //獲得接收服務器發送內容的輸入流
        BufferedReader in=new BufferedReader(new InputStreamReader(connection.getInputStream()));
        //從服務器獲得歡迎信息
        System.out.println("服務器信息:"+in.readLine());
        System.out.println("服務器信息:"+in.readLine());
        //提示用戶輸入
        System.out.print("請輸入>");
        boolean done=false;
        while(!done){
            //從鍵盤上讀取字符
            String line=stdin.readLine();
            //發送到服務端
            out.println(line);
            //如果讀到bye則結束循環
            if(line.equalsIgnoreCase("bye"))
                done=true;
            //從服務器讀取字符串
            String info=in.readLine();
            //顯示從服務器發送來的數據
            System.out.println("服務器信息:"+info);
            //提示用戶輸入
            if(!done)
                System.out.print("請輸入>");           
        }
        //關閉
        connection.close();
    }catch(SecurityException e){
        System.out.println("連接服務器出現安全問題!");
    }catch(IOException e){
        System.out.println("連接服務器出現I/O錯誤!");
    }
    }
}

package client;

public class ClientDemo {

    /**
     * @param args
     */
    public static void main(String[] args) {
        // TODO Auto-generated method stub
if(args.length!=2){
    System.out.println("程序運行方式:java client <服務器名稱><端口號>");
    return;
}
String host=args[0];
try{
    int port=Integer.parseInt(args[1]);
    Client myserver=new Client(host,port);
}catch(Exception e){
    System.out.println(e);
}
    }

}
二。點對面通信
服務端:
package server;

import java.io.IOException;
import java.net.ServerSocket;
import java.net.Socket;

public class Server extends ServerSocket {
private int port;
//private Socket connection;
public Server(int port)throws IOException{
    super(port);
    this.port=port;
    System.out.println("服務器啓動完成,監聽端口在"+port);
    System.out.println("正在等待客戶連接.....");
    try{
    while(true){
        //掛起,直到客戶請求
        Socket connection=accept();
        //建立服務線程
        new ServerThread(connection,port);
    }
    }catch(IOException e){
        System.out.println(e);
    }finally{
        close();
    }
}
}
package server;


import java.io.*;
import java.net.*;

public class ServerThread extends Thread{
private int port;
private Socket connection;
private BufferedReader in;
private PrintWriter out;
public ServerThread(Socket s,int port)throws IOException{
    this.port=port;
    this.connection=s;
    //獲取讀取客戶端的數據流
    // TODO Auto-generated method stub
if(args.length!=2){
    System.out.println("程序運行方式:java client <服務器名稱><端口號>");
    return;
}
String host=args[0];
try{
    int port=Integer.parseInt(args[1]);
    Client myserver=new Client(host,port);
}catch(Exception e){
    System.out.println(e);
}
    }

}
二。點對面通信
服務端:
package server;

import java.io.IOException;
import java.net.ServerSocket;
import java.net.Socket;

public class Server extends ServerSocket {
private int port;
//private Socket connection;
public Server(int port)throws IOException{
    super(port);
    this.port=port;
    System.out.println("服務器啓動完成,監聽端口在"+port);
    System.out.println("正在等待客戶連接.....");
    try{
    while(true){
        //掛起,直到客戶請求
        Socket connection=accept();
        //建立服務線程
        new ServerThread(connection,port);
    }
    }catch(IOException e){
        System.out.println(e);
    }finally{
        close();
    }
}
}
package server;


import java.io.*;
import java.net.*;

public class ServerThread extends Thread{
private int port;
private Socket connection;
private BufferedReader in;
private PrintWriter out;
public ServerThread(Socket s,int port)throws IOException{
    this.port=port;
    this.connection=s;
    //獲取讀取客戶端的數據流
     in=new BufferedReader(new InputStreamReader(connection.getInputStream

(),"gb2312"));
    //獲取寫往客戶端的數據輸出流,true表示自動刷新
     out=new PrintWriter(connection.getOutputStream(),true);
    //向客戶發送歡迎的信息
    out.println("您好,服務器連接成功!");
    out.println("輸入bye斷開與服務器的連接");
    //啓動線程
    start();
}
//將從客戶端收到的信息轉化爲大寫的
public String process(String line){
    return line.toUpperCase();
}
public void run(){
    try{
        boolean done=false;
        while(!done){
            String line=in.readLine();
            if(line==null)
                done=true;
            else{
                                if(line.trim().equals("bye"))
                    done=true;
                System.out.println("從客戶端來的內容"+line);
                String message=process(line);
                out.println("從服務器端口發出的內容"+message);           

   
            }
        }
System.out.println("bye bye!");
        //關閉通信
        connection.close();
    }catch(Exception e){
        System.out.println(e);
    }   
}
}
package server;

public class ServerDemo {

    /**
     * @param args
     */
    public static void main(String[] args) {
        // TODO Auto-generated method stub
if(args.length!=1){
    System.out.println("運行方式:java Server <端口號>");
    return;
}
try{
    //獲得端口號
    int port=Integer.parseInt(args[0]);
    Server myserver=new Server(port);
}catch(Exception e){
    System.out.println(e);
}
    }

}
客戶端:
package client;
import java.io.*;
import java.net.*;
public class Client {
private String host;
private int port;
public Client(String host,int port){
    this.host=host;
    this.port=port;
    connect();   
}
public void connect(){
    try{
        Socket connection;
        if(host.equals("localhost"))
            connection=new Socket(InetAddress.getLocalHost(),port);
        else
           connection=new Socket(InetAddress.getByName(host),port);   
        //獲得從鍵盤輸入流
        BufferedReader stdin=new BufferedReader(new InputStreamReader(System.in));
        //獲得服務器寫內容的數據流
        PrintWriter out=new PrintWriter(connection.getOutputStream(),true);
        //獲得接收服務器發送內容的輸入流
        BufferedReader in=new BufferedReader(new InputStreamReader(connection.getInputStream()));
        //從服務器獲得歡迎信息
        System.out.println("服務器信息:"+in.readLine());
        System.out.println("服務器信息:"+in.readLine());
        //提示用戶輸入
        System.out.print("請輸入>");
        boolean done=false;
        while(!done){
            //從鍵盤上讀取字符
            String line=stdin.readLine();
            //發送到服務端
            out.println(line);
            //如果讀到bye則結束循環
            if(line.equalsIgnoreCase("bye"))
                done=true;
            //從服務器讀取字符串
            String info=in.readLine();
            //顯示從服務器發送來的數據
            System.out.println("服務器信息:"+info);
            //提示用戶輸入
            if(!done)
                System.out.print("請輸入>");           
        }
        //關閉
文章出處:DIY部落(http://www.diybl.com/course/3_program/java/javashl/20081011/150076_2.html)

文章出處:file:///C:/Documents%20and%20Settings/pyh/Local%20Settings/Temp/Rar$EX02.250/java_socket2.htm

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章