我们一起学网络程序设计之二~~~~~~~~~~~~~~~~~~单项通信

我们一起学网络程序设计之二~~~~~~~~~~~~~~~~~~单项通信

Server.java2

mport java.net. * ;
import  java.io. * ;

public   class  Server2  {
   
private  BufferedReader reader;
   
private  Socket socket;
   
private  ServerSocket serve;
    
public  Server2()  {}
void  startServer() {
 
try {
  serve
= new  ServerSocket( 7777 );
  System.out.println(
" 服务器套接字创建完毕 " );
  
while ( true ) {
   System.out.println(
" 等待客户机 " );
   socket
= serve.accept();
   System.out.println(
" 完成与客户机的连接 " );
   reader
= new  BufferedReader( new  InputStreamReader(socket.getInputStream()));
   getMessage();
  }

 }
catch (Exception e) {
  System.out.println(e);
 }

}

void  getMessage() {
 
try {
  
while ( true ) {
   System.out.println(
" 客户机:  " + reader.readLine());
  }

 }
catch (Exception e) {} finally {
  
try {
   
if (reader != null ) reader.close();
   
if (socket != null ) socket.close();
  }
catch (IOException ie) {
  }

 }

}

    
public   static   void  main(String[] args)  {
        Server2 server
= new  Server2();
        server.startServer();
    }

}



Client2.java
import  java.awt. * ;
import  java.net. * ;
import  java.io. * ;
import  java.awt.event. * ;

public   class  Client2  extends  Frame {
   
private TextArea msgView=new TextArea();
   
private TextField sendBox=new TextField();
   
private PrintWriter writer;
   Socket socket;
    
public Client2(String title) {
        
super(title);
        msgView.setEditable(
false);
        add(msgView,
"North");
        add(sendBox,
"South");
        sendBox.addActionListener(
new ActionListener(){
        
public     void actionPerformed(ActionEvent e){
            writer.println(sendBox.getText());
            msgView.append(sendBox.getText()
+"\n");
            sendBox.setText(
"");
        }

        }
);
        pack();
    }

    
    
public     void connect(){
        
try{
            msgView.append(
"尝试与服务器连接\n");
            socket
=new Socket("192.168.1.22",7777);
            msgView.append(
"请输入待传字符串\n") ;
            writer
=new PrintWriter(socket.getOutputStream(),true);
        }
catch(Exception e){
            writer.println(
"连接失败");
        }

    }

    
public static void main(String[] args) {
        Client2 client
=new Client2("向服务器发送数据");
        client.setVisible(
true);
        client.connect();
    }

}

你可能感兴趣的:(我们一起学网络程序设计之二~~~~~~~~~~~~~~~~~~单项通信)