• java socket 最简单的例子(server 多线程)


    server 端

    import java.io.*; 
    import java.net.*; 
    public class Server2 {
    
        /**
         * @param args
         */
        public static void main(String[] args) {
            // TODO Auto-generated method stub
            ServerSocket s = null;
            try{
                s= new ServerSocket(5432);
            }
            catch(IOException e)
            {
                System.out.println(e);
                System.exit(1);
            }
            int i = 1;
            while(true)
            {
                
                try{
                    Socket cs = s.accept();
                    new ServerThread(cs).start();
                    System.out.println("接收了 第"+i+"个请求");
                    i++;
                }
                catch(IOException e)
                {
                    System.out.println(e);
                }
            }
        }
    
    }

    serverThread 类

    import java.io.*;
    import java.net.*;
    
    public class ServerThread extends Thread {
    	static String hello = "From Server: Hello world";
    	Socket sock;
    	public ServerThread(Socket s)
    	{
    		sock =s ;
    	}
    	public void run()
    	{
    		try{
    			InputStream in = sock.getInputStream();
    			DataInputStream din = new DataInputStream(in);
    			String name = din.readUTF();
    			OutputStream out = sock.getOutputStream();
    			DataOutputStream dos = new DataOutputStream(out);
    			dos.writeUTF(hello+"your name :"+name);
    			in.close();
    			out.close();
    			sock.close();
    		}
    		catch(IOException e)
    		{
    			System.out.println(e);
    		}
    	}
    }
    

    client 端

    import java.io.*; 
    import java.net.*; 
    
    public class Client 
    { 
    
    public Client() 
    { 
    try 
    { 
    Socket s = new Socket("127.0.0.1", 5432); 
    
    OutputStream out = s.getOutputStream(); 
    
    DataOutputStream dout = new DataOutputStream(out);
    
    dout.writeUTF("oftenlin");
    
    InputStream in = s.getInputStream();
    DataInputStream din = new DataInputStream(in);
    
    String st = din.readUTF();
    
    System.out.println(st);
    in.close();
    out.close();
    s.close(); 
    } 
    catch (IOException e) 
    {} 
    } 
    
    public static void main(String[] args) 
    { 
    new Client(); 
    } 
    }
  • 相关阅读:
    开始程序猿的生涯了
    将博客搬至CSDN
    java如何修改java.library.path并且不重启jvm也能生效
    JCEF 如何修改右键菜单项(JCEF在右键菜单中添加开发者选项-show dev tools)
    JS调用JCEF方法
    java cef3 禁止右键菜单项
    [java报错]Could not instantiate listener XXXXXX
    ThinkPhp的搭建
    phpMyAdmin的配置
    铁路局12306余票查询的实现
  • 原文地址:https://www.cnblogs.com/oftenlin/p/2816146.html
Copyright © 2020-2023  润新知