首页 > 代码库 > socket(一)

socket(一)

 1 package 线程安全的讨论; 2 import java.io.BufferedReader; 3 import java.io.IOException; 4 import java.io.InputStreamReader; 5 import java.io.PrintStream; 6 import java.net.ServerSocket; 7 import java.net.Socket; 8  9 public class Server {10      public static void main(String[] args) throws IOException {11           //创建月hi个ServerSocket,用于监听客户端Socket的连接请求12          ServerSocket ss=new ServerSocket(3000);13          System.out.println("服务器启动了");14          while(true)15          {16              17              Socket s=ss.accept();18              //输出流,输出到客户端19              PrintStream p=new PrintStream(s.getOutputStream());20              //输入流21              BufferedReader buf=new BufferedReader(new InputStreamReader(s.getInputStream()));22              23              24              //读取服务器端的信息,并echo到客户端,以bye结束25             System.out.println("accept"+s.getInetAddress());26              27             28                while(true)29                {30                    String line=buf.readLine();31                    if(line.equals("bye"))32                    {33                        System.out.println("good bye");34                        break;35                    }36                    else37                    {38                        System.out.println(line);39                    }40                    41                    42                }43          }44           45          46      }47 48 }

2.客户端

 

package 线程安全的讨论;import java.io.BufferedReader;import java.io.IOException;import java.io.InputStreamReader;import java.io.PrintStream;import java.net.Socket;import java.util.Scanner;public class Client {     public static void main(String[] args) {          try          {               Socket socket=new Socket("127.0.0.1",3000);               //将socket对应的输入流包装成BufferedReader               BufferedReader br=new BufferedReader( new InputStreamReader(System.in));                                                                   PrintStream pt=new PrintStream(socket.getOutputStream());                                          String line=null;               while((line=br.readLine()) != null)               {                   pt.println(line);                                  }                              br.close();               socket.close();          }          catch(IOException e)          {               e.printStackTrace();          }              }}

 

socket(一)