Write your own socket multithreaded communication

Source: Internet
Author: User
Tags connect socket getmessage readline

1 Socketclient.java Code


Package com.cpcnet.socket;
Import Java.io.BufferedOutputStream;
Import Java.io.BufferedReader;
Import Java.io.BufferedWriter;
Import Java.io.DataInputStream;
Import Java.io.DataOutputStream;
Import Java.io.File;
Import Java.io.FileOutputStream;
Import java.io.IOException;
Import Java.io.InputStreamReader;
Import Java.io.OutputStreamWriter;
Import Java.io.PrintWriter;
Import Java.net.Socket;
Import java.net.UnknownHostException;
Import java.util.ArrayList;
Import java.util.List;

Import Java.util.Scanner;
Import Com.cpcnet.util.MyLogger;
Import Com.cpcnet.util.PropertiesUtil;

Import Com.cpcnet.util.StringUtil;
	public class Socketclient {private MyLogger logger = new MyLogger (socketclient.class);
    public static String Cmd=propertiesutil.getprop ("Socket.properties", "CMD");  
    Private socket socket = NULL;  
    Private BufferedReader br = NULL;  
    
    private PrintWriter PW = null; public string Getthefiles (string cmd,list<string> gidlist) {this.logger.info ("SocKetclient.java getthefiles (String cmd,list<string> gidlist) cmd = "+ cmd + gidlist =" + gidlist);
    	Boolean flag = true;
        
    	String result = null;
    	String IP = propertiesutil.getprop ("socket.properties", "IP");
    	
    	int port = integer.parseint (Propertiesutil.getprop ("Socket.properties", "port"));
    		if (!this.connect (IP, port)) {this.logger.error ("Socketclient.java connect falied");
    	Flag = false;
    		}else{this.logger.info ("Socketclient.java connect Success");
    		This.logger.info ("Socketclient.java Connect socket =" + socket);
    		
    		 System.out.println ("socket=" + Socket);
				try {br = new BufferedReader (New InputStreamReader (Socket.getinputstream ()));  
			PW = new PrintWriter (new BufferedWriter (New OutputStreamWriter (Socket.getoutputstream)));
				catch (IOException e) {flag = false; This.logger.error ("Socketclient.java br = new BufferedReader (New InputStreamReader (Socket.getinputstream ())"; PW = New PrintWriter (New BufferedWriter OutputStreamWriter (Socket.getoutputstream ()));
				
				");
			E.printstacktrace ();
    			 } if (!this.sendcmd (cmd, gidlist)) {flag = false;
    			 
    		 This.logger.error ("Socketclient.java sendcmd (cmd, gidlist) failed");
    			 } if (flag) {result = This.getmessage ();
    		 System.out.println ("Socketclient.java result =" + result);
    	
    	} this.close ();
    	
    return result;
    	 public string GetMessage () {string result = NULL;
		String str = NULL;
			try {str = br.readline ();  
			SYSTEM.OUT.PRINTLN ("Server message =" +STR);
			result = STR;
		Thread.Sleep (1);
			catch (Exception e) {this.logger.error ("Socketclient.java getMessage () error");
		E.printstacktrace ();  
    	
    	
    	} pw.flush ();
    return result; public boolean sendcmd (String cmd,list<string> gidlist) {Boolean flag =True    		if (Cmd.equals (CMD) &&gidlist.size () > 0) {String gidliststring = stringutil.listtostring (gidlist);
    		 String gidliststring = Stringutil.gidstringconvertlist (gidstr) string sendcmd = cmd + "and" + gidliststring;  
             Pw.println (Sendcmd);
    		
    	Pw.flush (); }else{this.logger.error ("Socketclient.java sendcmd (String cmd,list<string> gidlist) cmd =" + cmd + "Gidlis
    		t = "+ gidlist");
    	Flag = false;
    return flag;
    	public boolean connect (String IP, int port) {Boolean flag = true;
		try {socket = new socket (IP, port);
			catch (IOException e) {flag = false;
		E.printstacktrace ();
    return flag;
			public void Close () {try {br.close ();  
	        Pw.close ();  
		Socket.close ();
			catch (IOException e) {//TODO auto-generated catch block This.logger.error (' Socketclient.java close () error '); E.printstacktrace ();
		} public static void Main (string[] args) {String cmd = propertiesutil.getprop ("socket
. Properties "," CMD ");
list<string> gidlist = new arraylist<string> ();
Gidlist.add ("20186");
Gidlist.add ("40435");
Gidlist.add ("40699");
    	
New Socketclient (). Getthefiles (cmd, gidlist); try {//Thread.Sleep (5000);//} catch (Interruptedexception e) {///TODO auto-generated catch Blo
CK//E.printstacktrace ();
    	}//List<string> gidList2 = new arraylist<string> ();
    	Gidlist2.add ("19934");
    	Gidlist2.add ("40435");
    	Gidlist2.add ("40699");
New Socketclient (). Getthefiles (cmd, gidList2);

        {20186=[all_sites_traffic_summary_201502.html, all_sites_traffic_summary_201503.html], 40435=[], 40699=[]}
 }  
 
}


2 Socketserver.java Code

Package com.cpcnet.socket;
Import Java.io.BufferedInputStream;
Import Java.io.BufferedReader;
Import Java.io.BufferedWriter;
Import Java.io.DataInputStream;
Import Java.io.DataOutputStream;
Import Java.io.File;
Import Java.io.FileInputStream;
Import java.io.IOException;
Import Java.io.InputStreamReader;
Import Java.io.OutputStreamWriter;
Import Java.io.PrintWriter;
Import Java.net.ServerSocket;
Import Java.net.Socket;
Import java.util.ArrayList;
Import Java.util.HashMap;
Import java.util.List;

Import Java.util.Map;
Import Com.cpcnet.util.ListUtil;
Import Com.cpcnet.util.MyLogger;

Import Com.cpcnet.util.PropertiesUtil;
	public class Socketserver {private ServerSocket serversocket = null;
	Private socket socket = NULL;
	Private BufferedReader br = NULL;
	private PrintWriter PW = null;
	Private MyLogger logger = new MyLogger (socketserver.class);
	Private String Cmd=propertiesutil.getprop ("Socket.properties", "CMD");
	Private String cmd = null; Private String gidliststring = Null
	Private String error = Propertiesutil.getprop ("socket.properties", "error");
		public boolean init () {Boolean flag = true;	
		int port = integer.parseint (Propertiesutil.getprop ("Socket.properties", "port"));
		Set the port number of the service port try {serversocket = new ServerSocket (port); catch (IOException e) {this.logger.error ("Socketserver.java serversocket = new ServerSocket (PORT);"
			Port = "+ Port";
			Flag = false;
		E.printstacktrace ();  
		} System.out.println ("ServerSocket Start:" +serversocket);
	return flag;
		
		public boolean Start () {Boolean flag = true;	
		if (!this.init ()) {This.logger.error ("Socketserver.java init () failed");
					}else{while (true) {try {socket = serversocket.accept ();
					System.out.println ("Connection Accept Socket:" + socket);
					Thread thread = this.initthread (socket, logger);
Thread.Start ();
					
				Thread.stop (); catch (IOException e) {this.logger.error ("Socketserver.java start") Init the BR and PW error ");
					try {socket.close ();
					catch (IOException E1) {//TODO auto-generated catch block E1.printstacktrace ();
					} e.printstacktrace ();
				return false;
	}} return flag;
			
			Public Thread initthread (final Socket socket, final MyLogger logger) {thread thread = new Thread (new Runnable () { public void Run () {try {//request received from client BR = new BufferedReader (New InputStreamReader Socket.getin
					 Putstream ())); Used to send the return information, you can not decorate so many IO streams using the buffer stream when sending data to be aware of the call. Flush () Method pw = new BufferedWriter (New OutputStreamWriter (so  
					
				Cket.getoutputstream ()), true);
				catch (IOException E1) {//TODO auto-generated catch block E1.printstacktrace (); }//while (true) {if (!this.getmessage ()) {Logger.error ("Socketserver.java Getm
		                	
		                Essage () failed "); }
		            	if (!this.sendmessage ()) {Logger.error ("Socketserver.java SendMessage () failed");
		    			try {thread.sleep (1);
		    			catch (Interruptedexception e) {//TODO auto-generated catch block E.printstacktrace ();
} System.out.println ("close socket and socket = + socket");
		    			
This.close ();
						public void Close () {try {br.close ()};
						Pw.close ();
Socket.close ();
				Serversocket.close ();
					catch (IOException e) {logger.error ("Socketserver.java Close () error");
				E.printstacktrace ();
				} public boolean GetMessage () {Boolean flag = true;
				String cmdandgidlistandmonth = null;
				try {cmdandgidlistandmonth = Br.readline ();
					catch (IOException e) {logger.error ("Socketserver.java getMessage () error");
					E.printstacktrace ();
				
				return false; } if (CmdandgidlistandMonth!= null) {System.out.println ("Socketserver.java cmdandgidlistandmonth =" + Cmdandgidlistandmonth);
					cmd = Cmdandgidlistandmonth.split ("and") [0];
					
				gidliststring = Cmdandgidlistandmonth.split ("and") [1];
			return flag;
				
				public Boolean SendMessage () {Boolean flag = true;
					if (Cmd.equals (CMD)) {String Filebasicpath = Propertiesutil.getprop ("Socket.properties", "Filebasicpath");
					map<string,list<string>> map_gid_list = new hashmap<string,list<string>> ();
					
					List gidlist = listutil.stringtolist (gidliststring); if (gidlist!= null && gidlist.size () > 0) {for (int i = 0; i < gidlist.size (); i + +) {String F
							Ilepath = Filebasicpath + gidlist.get (i);
							list<string> gid_list = This.getfilesbygid (FilePath);
						Map_gid_list.put ((String) gidlist.get (i), gid_list);
} System.out.println ("map_gid_list.tostring () =" + map_gid_list.tostring ());						Pw.println (Map_gid_list.tostring ());  
						
						
					Pw.flush ();
						
						}else{flag =false;
						
					Logger.error ("Socketserver.java sendmessage error:this.cmd =" + cmd + "this.gidlist =" + gidlist);
				
				
			} return flag; Public list<string> Getfilesbygid (String filePath) {list<string> List = new Arraylist<string> ()
				;
				File Sumamrygidfile = new file (FilePath);
				if (!sumamrygidfile.exists ()) Sumamrygidfile.mkdir ();
				file[] Childfiles = Sumamrygidfile.listfiles ();
						  if (childfiles!= null &&childfiles.length > 0) {for (int j = 0; J < Childfiles.length; J + +) {
							if (!childfiles[j].isdirectory ()) {String childfilename = Childfiles[j].getname (); Childfilename = Childfilename.split ("\.")
							[0];
							Childfilename = Childfilename.split ("_") [4];
						  List.add (Childfilename);
			}} return list;
		}
			 
		 }); Return THread;

    public static void Main (string[] AGRs) {Boolean flag = new Socketserver (). Start ();
 }  
}



Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.