一、一个客户端对应一个服务器
class Server{ ServerSocket ss; public void start(){ try { ss=new ServerSocket(38383);//创建一个服务端 while(true){ Socket s = ss.accept();//获取链接上的客户端 new Task(s).start(); } } catch (IOException e) { e.printStackTrace(); }finally{ try { ss.close(); } catch (IOException e) { e.printStackTrace(); } } }
private class Task extends Thread{ Socket socket; public Task(Socket s){ this.socket=s; } @Override public void run() { try { OutputStream out = socket.getOutputStream(); InputStream in = socket.getInputStream(); PrintWriter pw = new PrintWriter(new OutputStreamWriter(out, "utf-8"), true); BufferedReader br = new BufferedReader(new InputStreamReader(in, "utf-8")); pw.println("吃点啥"); while(true){ String req=br.readLine(); if (req.equals("都有啥")) { pw.println("山珍海味"); }else if (req.equals("bye")) { pw.println("欢迎下次光临"); break; }else{ pw.println("木有"+req); } } br.close(); pw.close(); socket.close(); } catch (Exception e) { e.printStackTrace(); } super.run(); } } }
public class ServerDemo {
public static void main(String[] args) { new Server().start(); } }
|
|
class Client{ Socket socket; public void start(){ try { socket=new Socket("192.168.11.145", 38383); InputStream in = socket.getInputStream(); OutputStream out = socket.getOutputStream(); PrintWriter pw = new PrintWriter(new OutputStreamWriter(out, "utf-8"), true); BufferedReader br = new BufferedReader(new InputStreamReader(in, "utf-8")); System.out.println(br.readLine()); Scanner sc = new Scanner(System.in); while( true){ String req = sc.nextLine(); pw.println(req); String resp=br.readLine(); System.out.println(resp); if ("欢迎下次光临".equals(resp)) { break; } } br.close(); pw.close(); socket.close(); } catch (Exception e) { e.printStackTrace(); } } } public class ClientDemo { public static void main(String[] args) { new Client().start(); } } |
二、群聊
class Server{ ServerSocket ss; List<Socket> sockets; public void start(){ try { ss=new ServerSocket(38383); sockets=new ArrayList<Socket>(); while(true){ Socket s = ss.accept(); sockets.add(s); new Task(s).start(); } } catch (Exception e) { e.printStackTrace(); }finally{ try { ss.close(); } catch (IOException e) { e.printStackTrace(); } } }
public class Task extends Thread{ Socket socket;
public Task(Socket s) { super(); this.socket = s; } @Override public void run() { try { InputStream in = socket.getInputStream(); BufferedReader br = new BufferedReader(new InputStreamReader(in,"utf-8")); while(true){ String line =br.readLine(); if (line==null) {//客户端发过来是空就关闭 br.close(); throw new RuntimeException("客户端已关闭"); } for(Socket s:sockets){ OutputStream out = s.getOutputStream(); PrintWriter pw = new PrintWriter(new OutputStreamWriter(out, "utf-8"), true); pw.println(line); } }
} catch (Exception e) { e.printStackTrace(); }finally{ try { socket.close(); sockets.remove(socket); } catch (IOException e) { e.printStackTrace(); } } } } } public class ChatServer {
public static void main(String[] args) { new Server().start(); } } |
|
public class MainActivity extends Activity {
ListView listview; List<String> chats; ArrayAdapter<String> adapter; EditText etNickName,etContent; TextView tvEmpty; LinearLayout llConnect,llChat; Socket socket; BufferedReader br; PrintWriter pw; Button btnconnetct,btnsend; boolean flag=true; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); initView(); listview.setAdapter(adapter);
}
private void initView() {
listview=(ListView) findViewById(R.id.listView1); chats=new ArrayList<String>(); adapter=new ArrayAdapter<String>(this, android.R.layout.simple_list_item_1,chats);
etNickName=(EditText) findViewById(R.id.nickName); etContent=(EditText) findViewById(R.id.content);
tvEmpty=(TextView) findViewById(R.id.nochat); listview.setEmptyView(tvEmpty);
llConnect=(LinearLayout) findViewById(R.id.connet); llChat=(LinearLayout) findViewById(R.id.ll_chat); btnconnetct=(Button) findViewById(R.id.btn_connect); btnsend=(Button) findViewById(R.id.btn_send);
}
public void connect(View v){ new Thread(){ public void run() { try { socket=new Socket("192.168.11.145", 38383); br = new BufferedReader(new InputStreamReader(socket.getInputStream(), "utf-8")); pw = new PrintWriter(new OutputStreamWriter(socket.getOutputStream(), "utf-8"), true);
//启动一个线程,时刻保持对服务器发送过来的信息 new Thread(){ public void run() { try { while(flag){ final String resp = br.readLine(); if (resp==null) { throw new RuntimeException("服务器已关闭"); }
//更新listview runOnUiThread(new Runnable() {
public void run() { chats.add(resp); adapter.notifyDataSetChanged(); } }); } } catch (Exception e) { e.printStackTrace(); } }; }.start();
runOnUiThread(new Runnable() {更新UI
@Override public void run() { llConnect.setVisibility(View.GONE); llChat.setVisibility(View.VISIBLE); } }); } catch (Exception e) { e.printStackTrace(); } }; }.start(); }
public void send(View v){ final String line = etContent.getText().toString(); if (TextUtils.isEmpty(line)) { return; }
new Thread(){ public void run() { String nickname =etNickName.getText().toString(); if (TextUtils.isEmpty(nickname)) { nickname="1602A学员"; } pw.println(nickname+":"+line); }; }.start(); }
@Override protected void onDestroy() { super.onDestroy(); try { socket.close(); flag=false; } catch (IOException e) { e.printStackTrace(); } } } |
|
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android" xmlns:tools="http://schemas.android.com/tools" android:layout_width="match_parent" android:layout_height="match_parent" android:orientation="vertical" tools:context=".MainActivity" >
<ListView android:id="@+id/listView1" android:layout_width="match_parent" android:layout_height="0dp" android:layout_weight="1" android:transcriptMode="alwaysScroll"> </ListView> <TextView android:id="@+id/nochat" android:layout_width="match_parent" android:layout_height="0dp" android:layout_weight="1" android:text="没有聊天内容……" android:gravity="center" android:textSize="30sp"/>
<LinearLayout android:id="@+id/connet" android:layout_width="wrap_content" android:layout_height="wrap_content" >
<EditText android:id="@+id/nickName" android:layout_width="wrap_content" android:layout_height="wrap_content" android:layout_alignParentBottom="true" android:layout_alignParentLeft="true" android:ems="10" android:hint="请输入昵称……" >
<requestFocus /> </EditText>
<Button android:id="@+id/btn_connect" android:layout_width="102dp" android:layout_height="wrap_content" android:onClick="connect" android:text="链接" /> </LinearLayout>
<LinearLayout android:id="@+id/ll_chat" android:layout_width="wrap_content" android:layout_height="wrap_content" android:visibility="gone" >
<EditText android:id="@+id/content" android:layout_width="wrap_content" android:layout_height="wrap_content" android:hint="请输入发送内容…………" android:ems="10" >
<requestFocus /> </EditText>
<Button android:id="@+id/btn_send" android:layout_width="wrap_content" android:layout_height="wrap_content" android:onClick="send" android:text="发送" /> </LinearLayout>
</LinearLayout> |