JavaJava Socket 通信演示样例

Posted liguangsunls

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了JavaJava Socket 通信演示样例相关的知识,希望对你有一定的参考价值。

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

这里举两个样例:

第一种是每次client发送一个数据,服务端就做一个应答。

(也就是要轮流发)

另外一种是client能够连续的向服务端发数据,服务端也能够连续向client发数据。(多线程)


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


PS: 一个聊天程序雏形

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


Demo 1:

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

client

/**
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:

/**
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);
	}
}


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

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

完整代码: https://github.com/MummyDing/socketChatDemo
【转载请注明出处】

作者:MummyDing

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






















以上是关于JavaJava Socket 通信演示样例的主要内容,如果未能解决你的问题,请参考以下文章

Python Socket 编程——聊天室演示样例程序

Java 实例演示-ServerSocket 和 Socket 通信实例

javajava 命令 Unable to open socket file: target process not responding or HotSpot VM not loaded

Python攻防-Socket通信建立TCP反向连接

Python攻防-Socket通信建立TCP反向连接

一起talk C栗子吧(第一百五十五回:C语言实例--获取socket通信地址)