관련 읽기 : Java 소켓 채팅방 프로그래밍 (ii) 소켓을 사용하여 단일 대화방을 구현합니다.
인터넷에서 채팅을 구현하기 위해 소켓을 사용하는 많은 예가 이미 있지만 많은 것을 보았으며 많은 문제가 있습니다.
여기서는 비교적 완전한 채팅 예제를 구현하고 논리를 설명합니다.
소켓은 비교적 크기 때문에 비교적 완전한 소켓 예제를 작성하기 위해 몇 가지 기사를 나누게됩니다.
여기서는 먼저 메시지 푸시를 실현하기 위해 서버-클라이언트 통신 및 클라이언트의 가장 간단한 기능을 구현합니다.
목적 : 서버는 클라이언트와 연결을 설정합니다. 클라이언트는 메시지를 서버로 보낼 수 있으며 서버는 메시지를 클라이언트에게 푸시 할 수 있습니다.
1. Java를 사용하여 소켓 채팅 서버를 만듭니다
1. SocketUrls는 IP 주소와 포트 번호를 결정합니다
public class socketurls {// ip 주소 공개 최종 정적 문자열 IP = "192.168.1.110"; // 포트 번호 공개 최종 정적 int 포트 = 8888;}2. 메인 프로그램 입구
public class main {public static void main (String [] args)은 예외 {new Chatserver (). initserver ();}} 던지기3. Bean Entity 클래스
userinfobean
public class main {public static void main (String [] args)은 예외 {new Chatserver (). initserver ();}} 던지기채팅 메시지 비안
공개 클래스 MessageBean은 userInfobean {private long messageid; // 메시지 idprivate long groupId; // 그룹 IdPrivate boolean isgoup; // 그룹 메시지 개인 int chattype; // 메시지 유형; 1, 텍스트; 2, 그림; 3, 짧은 비디오; 4, 5, 지리적 위치; 7, 비디오 컨텐츠 개인 컨텐츠; // 텍스트 메시지 개인 메시지; // ErrorCode; // ERROR CODE // GET/SET 메소드를 생략}}4. Chatserver Chat Service, 가장 중요한 프로그램
public class chatserver {// socket service private static sperversocket 서버; public gson = new Gson ();/*** 소켓 서비스 초기화*/public void initserver () {try {// 포트 8080 서버에서 고객 요청을 듣기 위해 서버 스킷을 만듭니다. Catch Blocke.printstacktrace ();}}/*** 메시지 관리를 작성하고 메시지 수신을 유지하고 계속 메시지를 받고*/private void createMessage () {try {system.out.println ( "사용자 액세스 대기 :"); // 클라이언트 요청 Socket Socket = Server.accept ()를 대기하고 대기합니다. 다른 소켓이 새로운 스레드에 가입하기를 기다리는 스레드 (new runnable () {public void run () {createmessage ();}}). start (); // 클라이언트 outputStream output = socket.getOutputStream ()으로 정보를 보냅니다. 스캐너 = 새 스캐너 (socket.getInputStream ()); new Thread (new Runnable () {public void run () {try {string buffer; while (true) {// console strin = 새 bufferedReader (system.in); buffer = strin.readline (); // a a stes as a the the the the the the the the the the the the a stealline에서 bufferedReader를 입력합니다. 끝에서 += "/n"; output.write(buffer.getBytes("utf-8")) ;// 데이터 출력을 보내십시오. 현재 소켓 (true) {true) {thread.sleep (500); // system.out.println ( "content :" + bff.readline ()); // 클라이언트 정보를 가져옵니다. MessageBean.getUername ()); system.out.println ( "내용 :" + messagebean.getContent ());}} // server.close ();} catch (exception e) {// 자동 생성 Catch Blocke.printstacktrace (); system.out.println ( "error :" + e.getmessage ());2. 안드로이드 측은 서버에 연결하기 위해 모바일 측면으로 사용됩니다.
1. Appliaction은 글로벌 채팅 서비스를 인스턴스화합니다
공개 클래스 chatappliaction은 application {public static chatserver chatserver; public static userinfobean userInfobean; @overridepublic void oncreate () {super.oncreate ();}}2. IP 주소와 포트 번호는 서버와 일치합니다.
3. 채팅 강도는 서버 측과 동일합니다.
4. XML 레이아웃. 로그인, 채팅
1. 로그인
<? xml version = "1.0"encoding = "utf-8"?> <linearLayout XMLNS : Android = "http://schemas.android.com/apk/res/android"Android : layout_width = "match_parent"android : layout_height = "mays_pa Rent "Android : Orientation ="vertical "> <edittextAndroid : id ="@+id/chat_name_text "Android : layout_width ="match_parent "Android : layou t_height = "wrap_content"Android : hint = "username"android : text = "admin"/> <edittextAndroid : id = "@+id/chat_pwd_text"android : layout_width = " match_parent "android : layout_height ="wrap_content "Android : hint ="password "android : text ="123123123a "Android : inputtype ="numberpassword " /> <buttonAndroid : id = "@+id/chat_login_btn"Android : layout_width = "match_parent"android : layout_height = "wrap_content"Android : hint = "login"/> </linearLayout>
2. 채팅
<? xml version = "1.0"encoding = "utf-8"?> <linearLayout xmlns : and android = "http://schemas.android.com/apk/res/android"xmlns : thool = "http://schemas.android.com/tools"Android : layout_width = "match_parent : layout_height ="match_parent " "수직"도구 : context = ". activity.mainactivity"> <scrollviewandroid : id = "@+id/scrollview"android : layout_width = "match_parent"android : layout_height = "0dp"Android : layout_weight = "0.9"> <linearlayoutandr OID : id = "@+id/chat_ly"android : layout_width = "match_parent"android : layout_height = "mays_parent"android : indroid : "vertical"> </linearlayout> </scrollview> <linearlayoutandroid : layout_width = "mays_par ENT "Android : Layout_Height ="Wrap_Content "Android : Orientation ="HorizOntal "> <editTextAndroid : id ="@+id/chat_et "android : layout_width ="0DP "Android : layout_height ="match_parent "andlayout_weight ="0.8 " /><ButtonAndroid:="@+id/send_btn"Android:layout_width="0dp"Android:layout_height="match_parent 길로이드:layout_weight="0.2"Android:text="send "/> </linearlayout> </linearlayout>
5. LoginActivity 로그인
Public Class LoginActivity는 AppComPatactivity를 확장합니다. {private edittext chat_name_text, chat_pwd_text; private button chat_login_btn; @overrideprotected void oncreate (bundle savedinstancestate) {super.oncreate (super.onstancestate); chatout.ctinate (r.layout. = (editText) findViewById (r.id.chat_name_text); chat_pwd_text = (editText) findViewById (r.id.chat_pwd_text); chat_login_btn = (button) findViewById (r.id.chat_login_btn); chat_login_btn.setononclicklistner (new View.onClickListener () {@OverRidePublic void onclick (view v) {if (getLogin (chat_name_text.getText.getText (). toString (). trim (), chat_pwd_text.getText (). toString (). trim ()) {getChatserver (); New -Entent (leginatt.,) MainActivity.class); startActivity (의도); finist ();}});} 개인 부울 getLogin (문자열 이름, 문자열 pwd) {if (textUtils.isempty (name) || textUtils.isempty (pwd))) false; if (name.equals ( "admin") && pwd.equd.equd.equd.equd. false;} private void getchatserver () {chatappliaction.chatserver = new Chatserver ();}}6. Mainactivity 채팅
공개 클래스 MainActivity는 AppComPatactivity {private linearlayout chat_ly; private textview left_text, right_view; private edittext chat_et; private button send_btn; private viewgroup.layoutparams layoutparams = new viewgroup.layoutparams (viewgroup.layoutparams.match_parent, viewgroup.layoutparams.wrap_content);@atriadeprotected void oncreate (Bundle SavedInstancestate) {super.oncreate (savedInstancestate); setContentView (r.layout.activity_main); chat_ly = (linearlayout) findViewByid (r.id.chat_ly); findViewById (r.id.chat_et); send_btn = (버튼) findViewById (r.id.send_btn); send_btn.setonClickListener (new View.onClickListener () {@OverRidePublic void onclick (View V) {chatappliaction.chatserver.sendmessage (chat_et.getText (). toString (). trim ()); chat_ly.addview (initrightView (chat_et.getText (). toString (). trim ()); // queeuchatappliasector.chatser.chatser.chatser.chatser.chatser.chatser.chatser.chatser.chatser.chatser.chatser.chatser.chatser.chatser.chatester.chatser.chatester.chatester.chatser. {@overridepublic void handlemessage (message msg) {if (msg.what == 1) {// 메시지를 전송 한 후 uichat_ly.addview (initleftView (msg.obj.tostring ());}); MessageContent) {right_view = new TextView (this); right_view.setlayoutparams (layoutparams); right_view.setgravity (view.focus_right); right_view.settext (messagecontext); legring right_view;}/** let MessageContent) {left_text = new TextView (this); left_text.setlayoutparams (layoutparams); left_text.setgravity (view.focus_left); left_text.settext (messagecontent); return_text;}}7. Chatserver 채팅 로직, 가장 중요한
공개 클래스 chatserver {private socket socket; private handler handler; private messagebean messagebean; private gson = new gson (); // 소켓 객체에서 출력 스트림을 가져 와서 printwriter printwriter printwriter; inputStream 입력; outputStream; dataOutputStream dataOutputStream; public chatserver ()를 구성합니다. {initmessage (); initchatserver ();}/*** 메시지 큐, 메시지 전달에 사용됩니다 ** @param handler*/public void setchathandler (handler handler) {this.handler = handler;} private void initchatserver () {// onevidestage (private void initchatserver) {// private voideder (private voide) = new MessageBean (); messageBean.setUserId (1); messageBean.setMessageId (1); MessageBean.SetchAttype (1); messageBean.setUserName ( "admin"); chatAppliaction.userinFobean = messagebean;}/*** @param contentmsg*/public void void void void void == null) {message message = handler.obtainmessage (); what.hat.hat = 1; usmer.obj = "서버가 닫혔습니다"; handler.sendMessage (resigns); return;} byte [] str = contentmsg.getBytes ( "utf-8"); // utf-8string aaa = new string (str) MessageJson = gson.tojson (messagebean);/*** 서버의 readline ()이 읽기를 차단하고 있기 때문에* Newline 문자 또는 출력 스트림이 끝날 수 없으면 차단 될 수 있으므로*/messagejson +=로서 서버가 전송되었음을 알리기 위해 JSON 메시지의 끝에 새로운 라인 문자가 추가됩니다. "/n"; output.write(messagejson.getBytes("utf-8")) ;// newline print output.flush (); // 서버가 즉시 문자열을 수신하도록 출력 스트림을 새로 고침} catch (Exception e) {e.printstacktrace (); log.e ( "test", "error :" + e.tostring ());}}/*** child 스레드에서 메시지를받습니다*/private void arcevemessage () {new Runnable () {@overridic void run () {@overrideppublic void run () {@overrideppublic void run (). 기본 포트 8080 소켓에 대한 클라이언트 요청 = 새로운 소켓 (Socketurls.IP, SocketUrls.port); // 소켓 객체에서 입력 스트림을 가져 와서 해당 버퍼드 리더 객체 인쇄기 (socket.getOutputStream ()); input = socket.getInputStream (outout = socket.getoutStream = getoutStream (); dataOutputStream (socket.getOutputStream ()); // 클라이언트 버퍼드 리더 BFF에서 정보를 얻습니다. bff = 새 bufferedReader (inputStreamReader (input)); // SERTER 정보 문자열을 읽습니다. " + line); message message = handler.obtainmessage (); messag {e.printstacktrace (); log.e ( "test", "error :" + e.tostring ());}}). start ();}}}그건 그렇고, 모든 코드가 완료되었습니다.
이 데모를 사용하면 휴대폰이 서버에 메시지를 보내고 서버를 휴대폰으로 보낼 수 있습니다.
이 데모는 푸시 함수로 간주 될 수 있지만 실제 푸시는 그렇게 간단하지 않습니다. 소켓의 초보자로서 소켓 프로그래밍 아이디어를 볼 수 있습니다.
위의 것은 편집기 (1)가 소켓을 사용하여 채팅 메시지 푸시를 구현하기 위해 소개 된 Java 소켓 채팅방 프로그래밍입니다. 모든 사람에게 도움이되기를 바랍니다. 궁금한 점이 있으면 메시지를 남겨 주시면 편집자가 제 시간에 모든 사람에게 답장을 드리겠습니다. Wulin.com 웹 사이트를 지원해 주셔서 대단히 감사합니다!