JAVA socket通信



这是我学SOCKET时敲得例子,非常简单,TCP协议:
客户端代码:
import java.net.*;
import java.io.*;
public class SocketClient{
public static void main(String args[]){
try{
//客户端连接服务器
      Socket socket1 = new Socket("127.0.0.1",1989);
      InputStream is = socket1.getInputStream();
      DataInputStream dis = new DataInputStream(is);
//客户端接受服务器端的信息
      System.out.println(dis.readUTF());
      dis.close();
      socket1.close();
    }
    catch(IOException e){
     System.out.println("IO异常");
     }
}
}
服务器代码:
import java.net.*;
import java.io.*;
public class SocketServer{
  public static void main(String args[]){
  try{
  ServerSocket ss = new ServerSocket(1989);
  Socket socket1 = ss.accept();
  OutputStream os = socket1.getOutputStream();
   DataOutputStream  dos = new DataOutputStream(os);
//服务器端发给客户端的信息
   dos.writeUTF("anyway,i need u!"+socket1.getInetAddress()+"port:"+socket1.getPort());
   dos.close();
   socket1.close();
    }
    catch(IOException e){
      System.out.println("IO错误!");
     }
  }
}

-------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------

public  class  Client {
     public  static  void  main(String[] args) {
         String s= null ;
         Socket mysocket;
         DataInputStream in= null ;
         DataOutputStream out= null ;
         try  {
             mysocket= new  Socket( "127.0.0.1" , 4331 );
             in= new  DataInputStream(mysocket.getInputStream());
             out= new  DataOutputStream(mysocket.getOutputStream());
             for ( int  k= 1 ;k< 100 ;k=k+ 2 ){
                 out.writeUTF( "" +k);
                 s=in.readUTF();
                 System.out.println( "客户收到" +s);
                 Thread.sleep( 500 );
             }
         catch  (Exception e) {
             System.out.println( "服务器已断开" +e);
         }
     }
}
 
public  class  Server {
     public  static  void  main(String[] args) {
         ServerSocket server= null ;
         Socket you= null ;
         String s= null ;
         DataOutputStream out= null ;
         DataInputStream in= null ;
         try  {
             server= new  ServerSocket( 4331 );
         catch  (Exception e) {
             System.out.println(e);
         }
         try  {
             System.out.println( "等待客户呼叫" );
             you=server.accept();
             out= new  DataOutputStream(you.getOutputStream());
             in= new  DataInputStream(you.getInputStream());
             while ( true ){
                 s=in.readUTF();
                 int  m=Integer.parseInt(s);
                 out.writeUTF( "你好,我是服务器" );
                 out.writeUTF( "你说的数乘2后是:" + 2 *m);
                 System.out.println( "服务器收到:" +s);
                 Thread.sleep( 500 );
             }
         catch  (Exception e) {
             System.out.println( "客户端已断开" +e);
         }
     }
}
 
很简单的服务器客户端程序

你可能感兴趣的:(socket,tcp)