码迷,mamicode.com
首页 > 编程语言 > 详细

java 简单实现socket

时间:2016-10-20 14:53:18      阅读:199      评论:0      收藏:0      [点我收藏+]

标签:

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

标签:

原文地址:http://www.cnblogs.com/luo-mao/p/5980419.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!