이 기사에서는 소켓을 기반으로 Java가 구현 한 클라이언트 및 서버 통신 기능에 대해 설명합니다. 다음과 같이 참조에 대해 공유하십시오.
다음 코드는 MA Soldier의 채팅 프로젝트를 나타냅니다. 먼저 chatserver.java를 실행하여 포트 청취를 구현 한 다음 chatclient.java를 실행하십시오.
클라이언트 인스턴스
chatclient.java
패키지 SocketDemo; import java.awt.*; import java.awt.event.*; import java.io.*; import java.net.*; public class chatclient는 프레임 {소켓 s = null; dataOutputStream dos = null; datainputStream dis = null; 개인 부울 bconnected = false; Textfield tftxt = new Textfield (); TextRea Tacontent = New TextRea (); 스레드 trecv = 새로운 스레드 (new recvthread ()); public static void main (string [] args) {new ChatClient (). 런치 프레임 (); } public void 런치 프레임 () {setLocation (400, 300); this.setsize (300, 300); 추가 (tftxt, borderlayout.south); 추가 (Tacontent, BorderLayout.north); 팩(); this.addwindowlistener (새 WindowAdapter () {@override public void WindowClosing (windowevent arg0) {distronnect (); system.exit (0);}}); tftxt.addactionListener (new tflistener ()); setvisible (true); 연결하다(); trecv.start (); } public void connect () {try {s = new Socket ( "localhost", 8888); dos = new DataOutputStream (s.getOutputStream ()); dis = new datainputStream (s.getInputStream ()); System.out.println ( "Connected!"); bconnected = true; } catch (unknownHostException e) {e.printstacktrace (); } catch (ioexception e) {e.printstacktrace (); }} public void dellonnect () {try {dos.close (); 드러내다(); s.close (); } catch (ioexception e) {e.printstacktrace (); } / * * try {bconnected = false; trecv.join (); } catch (InterruptedException * e) {e.printstacktrace (); } 마침내 {try {dos.close (); 드러내다(); * s.close (); } catch (ioexception e) {e.printstacktrace (); }} */} private class tflistener는 ActionListener를 구현합니다 {public void actionPerformed (ActionEvent e) {String str = tftxt.getText (). trim (); // tacontent.settext (str); tftxt.settext ( ""); try {// system.out.println (s); dos.writeutf (str); dos.flush (); // dos.close (); } catch (ioexception e1) {e1.printstacktrace (); }}} private class recvthread는 runnable {public void run () {try {while (bconnected) {String str = dis.readutf (); // system.out.println (str); tacontent.settext (tacontent.getText () + str + '/n'); }} catch (pocketexception e) {System.out.println ( "종료, bye!"); } catch (eofexception e) {system.out.println ( "예외, bye -bye!"); } catch (ioexception e) {e.printstacktrace (); }}}}소켓 서버 코드
chatserver.java
Package SocketDemo; import java.io.*; import java.net.*; import java.util.*; public class chatserver {boolean start = false; serversocket ss = null; 목록 <client> 클라이언트 = New ArrayList <client> (); public static void main (String [] args) {new Chatserver (). start (); } public void start () {try {ss = new serversocket (8888); 시작 = 참입니다. } catch (bindException e) {System.out.println ( "포트 사용 ......"); System.out.println ( "관련 프로그램을 닫고 서버를 다시 실행하십시오!"); System.exit (0); } catch (ioexception e) {e.printstacktrace (); } try {while (시작) {소켓 s = ss.Accept (); 클라이언트 C = 새 클라이언트; System.out.println ( "클라이언트 연결!"); 새 스레드 (c) .start (); clients.add (c); // dis.close (); }} catch (ioexception e) {e.printstacktrace (); } 마침내 {try {ss.close (); } catch (ioexception e) {// todo 자동 생성 캐치 블록 e.printstacktrace (); }}} 클래스 클라이언트 구현 실행 가능 {개인 소켓 s; private datainputStream dis = null; 비공개 dataOutputStream dos = null; 개인 부울 bconnected = false; 공개 클라이언트 (소켓 S) {this.s = s; try {dis = new DatainputStream (s.getInputStream ()); dos = new DataOutputStream (s.getOutputStream ()); bconnected = true; } catch (ioexception e) {e.printstacktrace (); }} public void send (string str) {try {dos.writeutf (str); } catch (ioexception e) {clients.remove (this); System.out.println ( "다른 당사자가 종료되었습니다! 목록에서 제거했습니다!"); // e.printstacktrace (); }} public void run () {try {while (bconnected) {string str = dis.readutf (); System.out.println (str); for (int i = 0; i <clients.size (); i ++) {client c = clients.get (i); C.send (str); // system.out.println ( "문자열 보내기!"); } / * * for (iterator <client> it = clients.iterator (); * it.hasnext ();) {client c = it.next (); C.send (str); } * / / * * iterator <client> it = clients.iterator (); * while (it.hasnext ()) {client c = it.next (); C.send (str); *} */}} catch (eofexception e) {system.out.println ( "클라이언트 닫기!"); } catch (ioexception e) {e.printstacktrace (); } 마침내 {try {if (dis! = null) dis.close (); if (dos! = null) dos.close (); if (s! = null) {s.close (); // s = null; }} catch (ioexception e1) {e1.printstacktrace (); }}}}}}로컬 테스트 실행 결과 :
클라이언트 창을 닫은 후 프롬프트 메시지는 다음과 같습니다.
Java 관련 컨텐츠에 대한 자세한 내용은이 사이트의 주제를 확인하십시오 : "Java 소켓 프로그래밍 기술 요약", "Java 파일 및 디렉토리 운영 기술 요약", "Java 데이터 구조 및 알고리즘에 대한 자습서", "Java 운영 Dom Node Skills의 요약"및 "Java Cache 운영 기술의 요약".
이 기사가 모든 사람의 Java 프로그래밍에 도움이되기를 바랍니다.