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(); 
    } 
    }
  • 相关阅读:
    用例图解析
    A B C D类网络地址
    B-树特征
    常用的中间代码
    UML图
    关于文件索引的一道习题
    数据流图的一些原则
    系统总线
    各种排序方法的时间复杂度、空间复杂度和稳定性统计表
    模拟银行自助终端系统
  • 原文地址:https://www.cnblogs.com/oftenlin/p/2816146.html
Copyright © 2011-2022 走看看