首页 > 代码库 > java 简单实现socket

java 简单实现socket

server端

package socket;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.PrintWriter;
import java.net.ServerSocket;
import java.net.Socket;

public class serverluo {

    public serverluo() 
     {try{
        ServerSocket ss=new ServerSocket(9999);//服务器端口
        System.out.println("服务器正在监听");
        Socket s=ss.accept();// 监听
        //System.out.println("22");
        InputStreamReader  iw=new InputStreamReader(s.getInputStream());//从客户端接收信息
        BufferedReader br=new BufferedReader(iw);
        
    //    System.out.println(s1);
        
        PrintWriter pw=new PrintWriter(s.getOutputStream(),true);//向客户端发送信息
        //pw.println("你好 客户端  你发送的信息我已收到!");
        InputStreamReader is=new InputStreamReader(System.in);//读取控制台的内容
        BufferedReader bd=new BufferedReader(is);
        
        while(true)
            {
            String s1=br.readLine();
            System.out.println("客户端说:"+s1+"\r\n");
            
            System.out.println("服务器说:"+"\r\n");
            
            String s2=bd.readLine();
            pw.println(s2);
            
            }
        
     }catch(Exception e){}
     }
    
    public static void main(String []args)
     {
        serverluo sl=new serverluo();
        
     }
}

 

client端

package socket;

import java.io.BufferedReader;
import java.io.InputStreamReader;
import java.io.PrintWriter;
import java.net.Socket;

public class client {
    
    public client()
      {try{
        Socket sk=new Socket("127.0.0.1",9999);
        PrintWriter pw=new PrintWriter(sk.getOutputStream(),true);//向服务器发送信息
        //pw.println("我是客户端");
        InputStreamReader is=new InputStreamReader(System.in);
        BufferedReader bb01=new BufferedReader(is);
        
        InputStreamReader im=new InputStreamReader(sk.getInputStream());//从服务器接收信息
        BufferedReader bb02=new BufferedReader(im);
        
        //System.out.println(s);
        
        
        while(true)
         {
            
            System.out.println("客户端说:");
            
            String s3=bb01.readLine();
            pw.println(s3);
            String s4=bb02.readLine();
            System.out.println("服务器说:"+s4+"\r\n");
            
            
         }
        
      }catch(Exception e){}
      }

    
    public static void main(String []args)
     {
        client cl=new client();
     }
}

 

java 简单实现socket