码迷,mamicode.com
首页 > 编程语言 > 详细

【Java】Java Socket 通信示例

时间:2015-06-10 21:04:59      阅读:129      评论:0      收藏:0      [点我收藏+]

标签:java   socket   通信   

用socket(套接字)实现客户端与服务端的通信。

这里举两个例子:

第一种是每次客户端发送一个数据,服务端就做一个应答。(也就是要轮流发)

第二种是客户端可以连续的向服务端发数据,服务端也可以连续向客户端发数据。(多线程)


为了方便起见,客户端服务端都放在一个主机上,分别开两个进程[哈哈,进程间通信lol~]


PS: 一个聊天程序雏形

代码也放在GitHub上了:https://github.com/MummyDing/socketChatDemo


Demo 1:

简单的Socket通信,一人一句话就结束了(要一直说加个循环就好)

客户端

/**
Client
Author :MummyDing
*/
import java.lang.Runnable; 
import java.io.*; 
import java.net.*;
class clientConnect{
	 	Socket client = null;
        BufferedReader inputData = null;   
        PrintWriter outputData = null;
        String receiveData ,sendData ;

        clientConnect(){
        	 try {
            client = new Socket("127.0.0.1", 5234);  
            dealData();
            }
        	catch (Exception e) {
        		System.out.println("I cann't Connect!");
            	System.exit(1);
        	}
    	} 
    	void dealData(){
    		try{
    		outputData = new PrintWriter(client.getOutputStream(), true);
    		inputData = new BufferedReader(new InputStreamReader(client.getInputStream())); 
             
 			 sendMsg();
 			 receiveMsg();	
    		}catch (Exception e) {
    			System.out.println("Error ~");
    		}
    		 
    	}
    	void sendMsg(){
    		outputData.println("Hello Server");
    	}
    	void receiveMsg(){
    		try{
    		receiveData =  inputData.readLine(); 
    		System.out.println("Server said "+receiveData);  	
    	}catch (Exception e) {
    		System.out.println("Error");
    	}
    		
    	}
}
public class Client  {
	public static void main(String[] args) { 
		clientConnect connecte = new clientConnect();  
	}
}


服务端:


/**
Server
Author :MummyDing
*/
import java.lang.Runnable; 
import java.net.*;
import java.io.*;
class serverConnect {
		ServerSocket serverSocket = null; 
		Socket clientSocket = null;
		String receiveData,sendData;
		serverConnect(){
			try {
        	serverSocket = new ServerSocket(5234);
        	clientSocket = serverSocket.accept();
        	dealData(); 
        }
        catch (Exception e) {  
        	System.out.println("Server Bulid Error");
        	System.exit(1);
        }
		}
		void dealData(){
			try{
			PrintWriter outputData = new PrintWriter(clientSocket.getOutputStream(), true);
			BufferedReader inputData = new BufferedReader(new InputStreamReader(clientSocket.getInputStream()));
			receiveData = inputData.readLine();  
			System.out.println("Client say:"+ receiveData);
			outputData.println("Ha ha , I got your info: "+receiveData);  
			}catch (Exception e) {
				System.out.println("Error!");
			}
		}
}
public class Server{
	public static void main(String[] args) { 
		serverConnect connecte = new serverConnect();		 
	}
}


Demo 2:


在Demo 1的基础上进行了该进,实现了一人可以连续说几句话。(多线程)


客户端:

/**
Client
Author:MummyDing
*/
import java.util.Scanner;
import java.lang.Runnable; 
import java.io.*; 
import java.net.*;
class clientConnect{
	 	Socket client = null;
        BufferedReader inputData = null;   
        PrintWriter outputData = null;
        String receiveData ,sendData ;
        clientConnect(){
        	 try {
            client = new Socket("127.0.0.1", 5234);  
            dealData();
            outputData.println("OK");
            }
        	catch (Exception e) {
        		System.out.println("I cann't Connecte!");
            	System.exit(0);
        	}
    	} 
    	void dealData(){
    		try{
    		outputData = new PrintWriter(client.getOutputStream(), true);
    		inputData = new BufferedReader(new InputStreamReader(client.getInputStream())); 
    		}catch (Exception e) {
    			System.out.println("Error ~");
                System.exit(0);
    		} 
    	}
    	String sendMsg(){
            Scanner sc = new Scanner(System.in);
            sendData = sc.nextLine();
    		outputData.println(sendData); 
            outputData.flush();
            System.out.println("I say:"+ sendData);
            return sendData;
    	}
    	boolean receiveMsg(){
    		try{
    		receiveData =  inputData.readLine(); 
            if(receiveData.equals("shutdown")) return false;
    		System.out.println("Server said "+receiveData);  	
    	    }catch (Exception e) {
    		  System.out.println("Error");
              System.exit(0);
    	    }	
            return true;
    	}
}
public class Client  {
	public static void main(String[] args) {
		clientConnect connect = new clientConnect();
		Thread t = new Thread(new Runnable(){
            public void run(){
               while(true){
                connect.dealData();
                if(connect.receiveMsg() == false){
                    System.out.println("SHUTDOWN!!!");
                    System.exit(0);
                }
                }
            }
        });
       t.start();
        while(connect.sendMsg().equals("shutdown") == false){ 
        }
        System.exit(0);
	}
}



服务端:


/**
Server
Author:MummyDing
*/
import java.util.Scanner;
import java.lang.Runnable; 
import java.net.*;
import java.io.*;
class serverConnect {
		ServerSocket serverSocket = null; 
		Socket clientSocket = null;
		String receiveData,sendData;
		PrintWriter outputData ;
		BufferedReader inputData;
		serverConnect(){
			try {
        	serverSocket = new ServerSocket(5234);
        	clientSocket = serverSocket.accept();
        }
        catch (Exception e) {  
        	System.out.println("Server Bulid Error");
        	System.exit(1);
        }
		}
		void dealData(){
			try{  
			 outputData = new PrintWriter(clientSocket.getOutputStream(), true);
			 inputData = new BufferedReader(new InputStreamReader(clientSocket.getInputStream()));
			}catch (Exception e) {
				System.out.println("Error!"); 
				System.exit(0);
			}
		}
		boolean receiveMsg(){
			try{
				receiveData = inputData.readLine(); 
				if(receiveData.equals("shutdown")) return false ;
				System.out.println("Client say:"+ receiveData);
			}catch (Exception e) {
				System.out.println("receive Error~");
				System.exit(0);
			}
			return true;
		}
		String sendMsg(){
			Scanner sc = new Scanner(System.in); 
			sendData = sc.nextLine(); 
			outputData.println(sendData);  
			outputData.flush();
			System.out.println("I say:"+ sendData);
			return sendData;
		}
}
public class Server{
	public static void main(String[] args) {
		serverConnect connect = new serverConnect();
		Thread t  = new Thread(new Runnable(){
			public void run(){
				while(true){
				connect.dealData();
				if(connect.receiveMsg() == false){
                    System.out.println("SHUTDOWN!!!");
                    System.exit(0);
                }
				}
			}
		});
		t.start();
		while(connect.sendMsg().equals("shutdown") == false){
		}
		System.exit(0);
	}
}


--------------------------------------------------

期间犯了一个很二的错误,客户端和服务端里面用了"同名类",这就导致后编译的把前面的"同名类"覆盖掉了。

【转载请注明出处】

作者:MummyDing

出处:http://blog.csdn.net/mummyding/article/details/46445675



【Java】Java Socket 通信示例

标签:java   socket   通信   

原文地址:http://blog.csdn.net/mummyding/article/details/46445675

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!