zoukankan      html  css  js  c++  java
  • 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(); 
    } 
    }
  • 相关阅读:
    百度云管家开机启动如何取消
    双语小说阅读:《谁动了我的奶酪》
    [Swift]方法
    Swift中的类型属性(静态变量)
    Swift 学习之二十一:?和 !(详解)
    苹果Swift可为Windows/Android开发软件了
    iOS7下滑动返回与ScrollView共存二三事
    swift c++ oc 混编
    RTOS
    STM32 RTC
  • 原文地址:https://www.cnblogs.com/oftenlin/p/2816146.html
Copyright © 2011-2022 走看看