java socket-TCP连接

  
  
  
  
  1. package test; 
  2.  
  3. import java.io.DataInputStream; 
  4. import java.io.DataOutputStream; 
  5. import java.io.IOException; 
  6. import java.net.InetSocketAddress; 
  7. import java.net.ServerSocket; 
  8. import java.net.Socket; 
  9. import java.net.SocketAddress; 
  10.  
  11.  
  12. public class GprsServer { 
  13.     public static Socket socket; 
  14.     public static ServerSocket ss=null
  15.     public static DataInputStream in; 
  16.     public static DataOutputStream out; 
  17.     public static final int PORT=8100
  18.      
  19.      
  20.     public static void main(String arg[])  
  21.     { 
  22.         try 
  23.         { 
  24.             SocketAddress remoteAddr=new InetSocketAddress(PORT); 
  25.             ss = new ServerSocket(); 
  26.             ss.bind(remoteAddr);//以上两句可用 ss = new ServerSocket(PORT); 
  27.             socket=ss.accept();//等待客户端连接,会阻塞进程 
  28.             in=new DataInputStream(socket.getInputStream()); 
  29.             out=new DataOutputStream(socket.getOutputStream()); 
  30.             while(true
  31.             { 
  32.                 if(!socket.isConnected()) 
  33.                 { 
  34.                     socket=ss.accept();//等待获取数据 
  35.                     in=new DataInputStream(socket.getInputStream()); 
  36.                     out=new DataOutputStream(socket.getOutputStream()); 
  37.                 } 
  38.                 byte[] result=new byte[712]; 
  39.                 byte wel[]=new byte[50]; 
  40.                 in.read(result);//会阻塞进程 
  41.                 System.arraycopy(result,0,wel,0,14); 
  42.                 String str=new String(wel,0,3);//若发送的字符长度小于数组长度,需限制转为string的长度,否则转换的成string有误 
  43.                 System.out.println("接收数据:"+str); 
  44.                 out.write(wel); 
  45.                 System.out.println("发送数据:"+str); 
  46.                 if(str.equalsIgnoreCase("bye")) 
  47.                     break
  48.             } 
  49.             System.out.println("close!"); 
  50.             socket.close();
  51.         } 
  52.         catch(Exception e) 
  53.         { 
  54.             e.printStackTrace(); 
  55.         } 
  56.     } 

 TCP Socket服务端,监听本地端口。客户端需要知道服务端的IP和端口

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