精华内容
下载资源
问答
  • socket工具类

    2018-01-31 20:22:37
    socket工具类// buffer.append(decodeUnicode(json.optJSONObject("data").getString("area")));//地区 //buffer.append(decodeUnicode(json.optJSONObject("data").getString("country")));//国家
  • Socket工具类

    2020-01-06 14:47:18
    Socket工具类 import java.io.*; import java.net.Socket; import java.net.UnknownHostException; import java.text.NumberFormat; public class SocketUtils { // Socket服务ip地址 public final static ...

    Socket工具类

    import java.io.*;
    import java.net.Socket;
    import java.net.UnknownHostException;
    import java.text.NumberFormat;
    
    public class SocketUtils {
    
        // Socket服务ip地址
        public final static String SOCKET_ID = "168.45.**.***";
        // 端口号
        public final static int PORT = 13083;
    
        Socket socket = null;
    
        public SocketUtils(String ip,int port) throws UnknownHostException, IOException {
            socket = new Socket(ip, port);
        }
    
        // 建立scoket连接,获取信息
        public static String socket(SocketPacketUtils socketPacket){
            SocketUtils socketUtil = null;
            try {
                socketUtil = new SocketUtils(SOCKET_ID, PORT);
            } catch (UnknownHostException e) {
                System.out.println("socket链接异常,链接信息:");
                e.printStackTrace();
            } catch (IOException e) {
                System.out.println("socket IO异常");
                e.printStackTrace();
            }
            String result = "";
            try {
                result = socketUtil.sentSocket(socketPacket);
            } catch (Exception e) {
                e.printStackTrace();
            }
            return result ;
        }
    
        //发送请求信息,获取响应信息
        public String sentSocket(SocketPacketUtils socketPacket) throws UnsupportedEncodingException, IOException{
            OutputStream output=null;
            InputStream input =null;
            output = socket.getOutputStream();
            //写数据发送报文
            System.out.println("报文:"+new String(socketPacket.getByteStream()));
            output.write(socketPacket.getByteStream());
            output.flush();
            //获得服务端返回的数据
            input = getInputStreamBySocket();
            byte[] bytes  = new byte[input.available()];
            input.read(bytes);
            String str = new String(bytes,"gbk");
            System.out.println("返回数据str:"+str);
            if(!str.equals("")){
                str = addXmlStr(str);
            }
            input.close();
            output.close();
            socket.close();
            return str;
        }
    
    	private InputStream getInputStreamBySocket() throws IOException {
            InputStream input;
            int count = 0;
            while (true){
                input = socket.getInputStream();
                if(input.available()>0||count==75){
                    break;
                }
                try {
                    Thread.sleep(200);
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
                count++;
            }
            return input;
        }
    
    
        private String addXmlStr(String str) {
            //清空换行
            String s = str.replaceAll("\n","");
            return s;
        }
    
    
    
    }
    
    
    展开全文
  • java socket工具类示例

    2019-04-17 22:31:13
    java socket工具类示例,使用控制台实现简单收发,简单聊天系统.
  • socket工具类
    import java.io.BufferedInputStream;
    import java.io.ByteArrayOutputStream;
    import java.io.DataInputStream;
    import java.io.DataOutputStream;
    import java.net.Socket;
    
    public class SocketHelper {
    
        private String ip = null;
        private int port = 0;
        private Socket socket = null;
        private DataOutputStream outputStream = null;
        private DataInputStream inputStream = null;
    
        public SocketHelper(String ip, int port) {
            this.ip = ip;
            this.port = port;
        }
    
        public void createConnection() throws Exception {
            try {
                socket = new Socket(ip, port);
                socket.setKeepAlive(false);
            } finally {
                if (socket != null) {
                    socket.close();
                }
            }
        }
    
        public synchronized void sendMessage(String sendMessage) throws Exception {
            try {
                if (outputStream == null) {
                    outputStream = new DataOutputStream(socket.getOutputStream());
                }
                byte b[] = sendMessage.getBytes("GBK");
                outputStream.write(b);
                outputStream.flush();
            } finally {
                if (outputStream != null) {
                    outputStream.close();
                }
            }
        }
    
        public synchronized String getMessage() throws Exception {
            return getMessage(-1);
        }
    
        public synchronized String getMessage(int readSize) throws Exception {
            try {
                if (inputStream == null) {
                    inputStream =
                            new DataInputStream(
                                    new BufferedInputStream(
                                            socket.getInputStream()));
                }
                ByteArrayOutputStream byteArrayOutputStream = new ByteArrayOutputStream();
                if (inputStream != null) {
                    if (readSize != -1 && readSize > 0) {
                        for (int i = 0; i < readSize; i++) {
                            int read = inputStream.read();
                            if (read == -1) {
                                break;
                            } else {
                                byteArrayOutputStream.write(read);
                            }
                        }
                    } else {
                        while (true) {
                            int read = inputStream.read();
                            if (read <= 0) {
                                break;
                            } else {
                                byteArrayOutputStream.write(read);
                            }
                        }
                    }
                    return new String(byteArrayOutputStream.toByteArray(), "GBK");
    
                }
            } finally {
                if (inputStream != null) {
                    inputStream.close();
                }
            }
            return null;
        }
    
        public void shutDownConnection() {
            try {
                if (outputStream != null) {
                    outputStream.close();
                }
                if (inputStream != null) {
                    inputStream.close();
                }
                if (socket != null) {
                    socket.shutdownInput();
                    socket.shutdownOutput();
                    socket.close();
                }
            } catch (Exception e) {
            }
        }
    
        public static void main(String[] args) throws Exception {
            String ip = "127.0.0.1";
            int port = 8080;
            String send = "待发送的信息";
    
            SocketHelper socketHelper = null;
            String recvMsg = null;
            try{
                socketHelper = new SocketHelper(ip, port);
                socketHelper.createConnection();
                socketHelper.sendMessage(send);
                recvMsg = socketHelper.getMessage();
            } finally {
                socketHelper.shutDownConnection();
            }
            System.out.println("服务器返回信息:" + recvMsg);
        }
    
    }

    展开全文
  • java socket工具类

    千次阅读 2019-04-17 22:28:25
    服务端 package server; import java.io.DataInputStream; import java.io.DataOutputStream; import java.io.IOException; import java.io.InputStream; import java.net....import java.net.Socket; ...

    服务端

    package server;
    
    import java.io.DataInputStream;
    import java.io.DataOutputStream;
    import java.io.IOException;
    import java.io.InputStream;
    import java.net.ServerSocket;
    import java.net.Socket;
    
    
    public class Servertools {
    
    	private	ServerSocket sersoc;
    	public Socket clisoc[]=new Socket[20];
    	
    	private	DataOutputStream out;
    	private	InputStream inFromClient;
    	private DataInputStream in;
    	
    	/**
    	 * 服务端类构造方法
    	 * @param port
    	 */
    	Servertools(int port){
    		try {
    			sersoc=new ServerSocket(port);
    			clisoc[0]=sersoc.accept();
    			inFromClient = clisoc[0].getInputStream();
    			in = new DataInputStream(inFromClient);			
    		} catch (IOException e) {
    			e.printStackTrace();
    		}
    		this.read();//开启读取线程		
    	}
    	
    	/**
    	 * socket服务端类发送消息方法
    	 * @param mes
    	 * @param clientsoc
    	 */
    	public void send(String mes,Socket clientsoc) {
    		
    		try {
    			out = new DataOutputStream(clientsoc.getOutputStream());
    			out.writeUTF(mes);	
    
    		}catch(IOException e) {
    			System.out.println("socket~server发送失败:"+e);		
    		}				
    	}
    	
    	
    	/**
    	 * socket服务端类读取消息方法
    	 */
    	public void read() {
    		Readthread rt=new Readthread();
    		rt.start();
    	}
    	
    	
    	/**
    	 * socket服务端读取线程类
    	 * @author Administrator
    	 *
    	 */
    	public class Readthread extends Thread{
    
    		public void run() {
    			
    			while(true)
    			{
    				try {
    					String tempstr=in.readUTF();
    					//System.out.println("socket~client收到消息:"+tempstr);	
    					Server.readit(tempstr);//调用主类读取中断方法
    				
    				}catch(IOException e) {
    					try {
    						Thread.sleep(1000);
    					} catch (InterruptedException ee) {
    						ee.printStackTrace();
    					}
    				}				
    			}				
    		}
    	}
    	
    		
    	/**
    	 * socket服务端类关闭方法
    	 */
    	public void close() {
    		try {
    			out.close();
    			clisoc[0].close();
    		}catch(IOException e) {
    			System.out.println("socket~server关闭失败:"+e);
    		}		
    	}
    }
    

    在使用类中实现 "Server.readit(tempstr);//调用主类读取中断方法" 静态方法即可获得传输过来的数据Server为类名

     

    客户端

    package client;
    
    import java.io.DataInputStream;
    import java.io.DataOutputStream;
    import java.io.IOException;
    import java.io.InputStream;
    import java.io.OutputStream;
    import java.net.Socket;
    
    public class Clienttools {
    
    	private Socket clisoc;
    	private OutputStream outtoserver;
    	private DataOutputStream out;
    	
    	private InputStream inFromServer;
    	private DataInputStream in;
    	
    	/**
    	 * socket客户端类构造方法
    	 * @param ip
    	 * @param port
    	 */
    	Clienttools(String ip,int port){
    		try {
    			//输出流区
    			clisoc=new Socket(ip,port);
    			outtoserver=clisoc.getOutputStream();
    			out=new DataOutputStream(outtoserver);		
    			//输入流区
    			inFromServer = clisoc.getInputStream();
    			in = new DataInputStream(inFromServer);			
    		}catch(IOException e) {
    			System.out.println("socket~client创建失败:"+e);		
    		}
    		this.read();
    	}
    	
    	
    	/**
    	 * socket客户端类发送消息方法
    	 * @param mes
    	 */
    	public void send(String mes) {
    		try {
    			out.writeUTF(mes);	
    		}catch(IOException e) {
    			System.out.println("socket~client发送失败:"+e);		
    		}				
    	}
    
    	
    	/**
    	 * socket客户端类读取消息方法
    	 */
    	public void read() {
    		Readthread rt=new Readthread();
    		rt.start();
    	}
    
    	
    	/**
    	 * socket客户端读取线程类
    	 * @author Administrator
    	 *
    	 */
    	public class Readthread extends Thread{
    		public void run() {	
    			while(true)
    			{
    				try {
    					String tempstr=in.readUTF();
    					//System.out.println("socket~client收到消息:"+tempstr);	
    					Client.readit(tempstr);//调用主类读取中断方法
    				
    				}catch(IOException e) {
    					try {
    						Thread.sleep(1000);
    					} catch (InterruptedException ee) {
    						ee.printStackTrace();
    					}
    				}				
    			}								
    		}
    	}
    	
    		
    	/**
    	 * socket客户端类关闭方法
    	 */
    	public void close() {
    		try {
    			out.close();
    			outtoserver.close();
    			clisoc.close();
    		}catch(IOException e) {
    			System.out.println("socket~client关闭失败:"+e);
    		}			
    	}
    }

    同样在实用类中实现静态方法"Client.readit(tempstr);//调用主类读取中断方法"  (Client为类名) 获得服务端传来的数据

    需要不同类型的数据传输时,修改输出流的write方法即可.

    声明:转载请注明出处,本人入门级菜鸟,内容大多学习于网络,存在问题太多不一一列举,大佬多多指教.本人QQ941131649

    展开全文
  • 简单的socket工具类

    2019-08-20 09:43:52
    #我是刚刚毕业的小白,在公司项目的过程中需要与公司服务器对接socket,模仿写了一个小的简单的socket工具类,在此写博客是为了加深自己的印象,欢迎各位大神指点,也为同样的小白给出点思路。废话不多说直接贴...

    Webscoket简单的连接、发送消息和读取服务器返回的消息

    #我是刚刚毕业的小白,在公司项目的过程中需要与公司服务器对接socket,模仿写了一个小的简单的socket的工具类,在此写博客是为了加深自己的印象,欢迎各位大神指点,也为同样的小白给出点思路。废话不多说直接贴代码。

    public class ScoketUtil {
        /**
         * ip     ip地址
         * port   端口
         * DataOutputStream   输出流
         * DataInputStream    输入流
         * */
        String ip = "192.168.1.115";
        int port = 8001;
        DataOutputStream dos = null;
        Socket soc = null;
        DataInputStream dis = null;
        public static String data;
    
    
        public static void setData(String data) {
            ScoketUtil.data = data;
        }
    
      /**
       * socket  登录
       * */
        public void  Login(){
            new Thread(){
                @Override
                public void run() {
                    if (soc == null) {
                        try {
                            soc = new Socket(ip, port);
                            //获取socket的输入输出流
                            dis = new DataInputStream(soc.getInputStream());
                            dos = new DataOutputStream(soc.getOutputStream());
                            setData("user login user=admin;password=admin;");  // 这里需要登录用户名和密码所以要发送登录的指令
                            send();
                            read();
                        } catch (IOException e) {
                            // TODO Auto-generated catch block
                            e.printStackTrace();
                        }
                    }
                }
        }.start();
    }
    /**
     * 发送消息
     * */
           public void send(){
            new Thread(){
                public  void  run(){
                    try {
                        System.out.println(data);
                        soc.getOutputStream().write(data.getBytes());
                        soc.getOutputStream().flush();
                    } catch (IOException e) {
                        // TODO Auto-generated catch block
                        e.printStackTrace();
                    }
                }
            }.start();
           }
           /**
            * 读取服务器的返回消息
            * */
           public void read(){
               new Thread(){
                   public  void  run(){
                       while (true){
                           try {
                               byte[] b = new  byte[1024];
                               soc.getInputStream().read(b);
                               System.out.println(new String(b));
                           } catch (IOException e) {
                               // TODO Auto-generated catch block
                               e.printStackTrace();
                           }
                       }
                   }
               }.start();
           }
    
    }
    
    
    展开全文
  • android Socket工具类

    2018-01-13 15:28:08
    通过Socket进行读,写操作(以下代码可以直接负责使用) public class SocketUtil {  private static String line;  Socket socket = null;  String ip = "192.168.10.107";  int port = 6000; ...
  • Android socket 工具类

    2018-03-21 17:06:10
    * 通过NIO方式进行socket链接 * */ public class MySocket_2 { /** 信道选择器 */ private Selector mSelector; /** 服务器通信的信道 */ private SocketChannel mChannel; /** 远端...
  • android socket工具类

    千次阅读 2017-05-15 17:55:29
    Socket C_socket = new Socket("127.0.0.1", port);//这里改ip和端口 //socket的输入流和输出流 java.io.OutputStream os = C_socket.getOutputStream(); BufferedWriter C_BW = new BufferedWriter(new ...
  • socket工具类-001

    2019-09-19 01:38:53
    public static void sendMessageByDataOutputStream(Socket socket, String message) { if (socket == null || socket.isClosed()) { return; } OutputStream outputStream = null; try...
  • } #endif /* GRPC_UV */ grpc windows 的实现 H:\EDUDEV\serviceMesh\grpc\grpc\src\core\lib\iomgr\socket_utils_windows.cc #include #include "src/core/lib/iomgr/port.h" #ifdef GRPC_WINDOWS_SOCKETUTILS #...
  • Socket自定义工具类

    2020-10-29 17:04:48
    单例定义的Socket工具类 线程池工厂保护内存 无侵入/功能单一:不处理数据,只负责获取和回传 Timer替代while循环,避免阻塞,读流时可以也使用while循环 重连策略 持续5秒未收到任何数据,给到客户端断开反馈 加锁...
  • socket通讯工具类

    千次阅读 2017-09-15 15:52:12
    socket通讯工具类
  • /** * @描述: TODO 服务器端: 本例为通过Socket编程实现从 服务器端 发送文件到 客户端 * @名称: FileServer * @作者: 宋延军 * @邮箱: songyanjun_stars@126.com * @日期: Feb 14, 2012 11:57:47 AM */ ...
  • Socket请求工具类

    2020-09-28 15:47:20
    socket_util import org.slf4j.Logger; import org.slf4j.LoggerFactory; import java.io.*; import java.net.ServerSocket; import java.net.Socket; import java.net.UnknownHostException; public class ...
  • Socket通讯工具类【SocketTools】

    千次阅读 2014-03-17 17:54:42
    /// /// Socket通讯工具类 /// public class SocketTools { private Socket mClient; private MemoryStream mMemo = new MemoryStream(); /// /// 当前连接状态:是否已经连接
  • 很强大的最底层的socket文件上传功能
  • #ifndef TCP_UDP_SOCKET_HPP #define TCP_UDP_SOCKET_HPP #include #include #include #pragma comment (lib,"ws2_32.lib") typedef struct DataHead { char szID[4]; int option; int dataLen; } class T
  • Java聊天室 IO流 Socket流 GUI界面 工具类Utils代码及解释(FileUtils文件发送的工具类Utils PathUtils是设置背景图片的图片路径Utils工具类 ScreenUtils是获取电脑屏幕大小的工具 BackGroundPanel图片绘制工具类) ...
  • java工具类 ftp 文件比较 socket http
  • NULL 博文链接:https://jyao.iteye.com/blog/1329615
  • socket工具源码

    2013-06-27 16:23:18
    建立Socket测试服务器端和测试客户端,并向其他端发送或接受报文数据,支持自动发送和自动应答,支持UDP和TCP; 2.录入的IP地址和端口等参数数据进行本地XML序列化,下次自动打开。(这个是我需要的,不用每次都...

空空如也

空空如也

1 2 3 4 5 ... 20
收藏数 1,345
精华内容 538
关键字:

socket工具类