socket通信联系程序
/**2005.10.10* for study JAVA TCP**/import java.io.*;import java.net.*;public class TCPReceive{ public static void main(String[] args) { System.out.println("Listenering..."); // ServerSocket ss; Socket client; try { ss = new ServerSocket(20000); // begain to accept for(;;) { client = ss.accept(); //得到输出流 OutputStream out = client.getOutputStream(); // 得到输入流 InputStream in = client.getInputStream(); byte[] in_buf = new byte; byte[] out_buf = {0X4C,0X58,0X46, 0X01,0,0,0,0,0,0X03,0,0,0,0,0,0X01, 0X46,0X4A,0X52, 0X0D,0X04, 0X01,0X02,0X06,0X31,0X30,0X30,0X30,0X32,0X35, 0X04,0X02,0X03,0X31,0X33,0X35, 0X0C,0X01,0X01, 0X05,0X01,0X01 }; for(;;) { while(in.read(in_buf) == 0) try { Thread.sleep(500); }catch(Exception ec){} System.out.println(new String(in_buf)); if(in_buf == 0x00) break; try { Thread.sleep(1000); }catch(Exception ec){} out.write(out_buf, 0, 42); for(int i = 0; i < 100; i++) in_buf = 0x00; } in.close(); out.close(); client.close(); } } catch(IOException e) { System.err.println(e); } }//end of main() } //end of class TCPReceive/**2005.10.10* for study JAVA TCP**/import java.io.*;import java.net.*;import java.net.SocketAddress;public class TCPSend{ public static void main(String[] args) { // Socket sender; try { SocketAddressaddr = new InetSocketAddress("10.10.6.235", 20000); do { sender = new Socket(); try { sender.connect(addr,5000); } catch(IOException ioe){} System.out.println("connecting..."); }while(sender.isBound() == false); // get outputstream OutputStream out = sender.getOutputStream(); //get inputstream InputStream in = sender.getInputStream(); byte[] in_buf = new byte; for(;;) { if(sending(out) == 0) break; // System.out.println("sending over!"); }//end of for try { Thread.sleep(1000); } catch(Exception ec){} in.close(); out.close(); sender.close(); } catch(IOException e) { System.err.println(e);// System.out.println("here"); } // catch(UnknownHostException e)// {// System.err.println("");// } //总是报错,找不到主机 } public static int sending(OutputStream out) { byte[] data = new byte; System.out.println("INPUT:"); try { System.in.read(data); if(data == 0x00) return(0);// String data1 = new String(data); try { //suggest use write(byte[], int, int) instand of write(byte[]), for more information //lookup JAVA DOC out.write(data, 0, data.length); } catch(IOException ioe){} } catch(Exception e){} return(1); }//end of sending() }
页:
[1]