이 기사에서는 참조를 위해 Java Socket Byte 스트리밍의 예를 공유합니다. 특정 내용은 다음과 같습니다
서버 측 :
패키지 com.yuan.socket; import java.io.*; import java.net.serversocket; import java.net.socket;/*** Yuan이 2016-09-17에 작성했습니다. */public class talkserver4byte {private serversocket server; 개인 int 포트 = 5020; public talkserver4byte () {try {server = new serversocket (port); } catch (ioexception e) {}} public void talk () {System.out.println ( "모니터 포트 :" + 포트); 소켓 소켓 = null; while (true) {try {// 차단 및 대기, 모든 요청에 대한 새 연결 인스턴스를 생성하십시오. System.out.println ( "클라이언트 연결 :" + socket.getRemotesocketAddress ()); // Decorative Stream BufferedReader는 입력 스트림 (클라이언트 수신) BufferedInputStream BIS = New BufferedInputStream (socket.getInputStream ()); datainputStream dis = new DatainputStream (BIS); 바이트 [] 바이트 = 새로운 바이트 [1]; // 한 번에 하나의 바이트를 읽습니다. ret = ""; while (dis.read (bytes)! = -1) {ret + = bytestohexstring (bytes) + ""; if (dis.available () == 0) {// 요청 dosomething (ret); }}} catch (ioexception e) {System.out.println (e.getMessage ()); } 마침내 {try {socket.close (); } catch (ioException e) {System.out.println (e.getMessage ()); }}}} public static void dosomething (String Ret) {System.out.println (ret); } public static string bytestohexstring (byte [] src) {StringBuilder StringBuilder = new StringBuilder ( ""); if (src == null || src.length <= 0) {return null; } for (int i = 0; i <src.length; i ++) {int v = src [i] & 0xff; 문자열 hv = integer.tohexstring (v); if (hv.length () <2) {StringBuilder.append (0); } StringBuilder.Append (HV); } return stringBuilder.toString (); } public static string byteshexstring (byte [] b) {String ret = ""; for (int i = 0; i <b.length; i ++) {string hex = integer.tohexstring (b [i] & 0xff); if (hex.length () == 1) {hex = '0' + hex; } ret += hex.toupperCase (); } return ret; } public static void main (String [] args) {talkServer4Byte Server = new TalkServer4Byte (); server.talk (); }} 클라이언트 클라이언트 코드 :
package com.yuan.socket; import java.io.datainputstream; import java.io.dataoutputStream; import java.io.ioexception; import java.io.inputstream; import java.net.inputsocketaddress; import java.net.socket; import java.net.net.net.socketAddress;/** on 2016--17에서 생성됩니다. */public class talkclient4byte {개인 소켓 소켓; 비공개 소켓 드레스 주소; public talkclient4byte () {try {socket = new Socket (); 주소 = 새로운 inetSocketAddress ( "127.0.0.1", 5020); socket.connect (주소, 1000); } catch (ioexception e) {e.printstacktrace (); }} public void talk () {try {// DatainputStream을 사용하여 입력 스트림 inputStream os = new DatainputStream (System.In); 바이트 [] B = 새로운 바이트 [1]; dataOutputStream dos = 새로운 dataOutputStream (socket.getOutputStream ()); while (-1! = os.read (b)) {dos.write (b); // 클라이언트로 보내} dos.flush (); dos.close (); } catch (ioexception e) {e.printstacktrace (); } 마침내 {try {socket.close (); } catch (ioexception e) {}}} public static void main (String [] args) {talkClient4byte client = new TalkClient4byte (); client.talk (); }}위는이 기사의 모든 내용입니다. 모든 사람의 학습에 도움이되기를 바랍니다. 모든 사람이 wulin.com을 더 지원하기를 바랍니다.