Socket是TCP/IP協(xié)議上的一種通信,在通信的兩端各建立一個Socket,從而在通信的兩端之間形成網(wǎng)絡(luò)虛擬鏈路。一旦建立了虛擬的網(wǎng)絡(luò)鏈路,兩端的程序就可以通過虛擬鏈路進(jìn)行通信。
Client A 發(fā)信息給 Client B , A的信息首先發(fā)送信息到服務(wù)器Server ,Server接受到信息后再把A的信息廣播發(fā)送給所有的Clients
首先我們要在服務(wù)器建立一個ServerSocket ,ServerSocket對象用于監(jiān)聽來自客戶端的Socket連接,如果沒有連接,它將一直處于等待狀態(tài)。
Socket accept():如果接收到一個客戶端Socket的連接請求,該方法將返回一個與客戶端Socket對應(yīng)的Socket
Server示例:
//創(chuàng)建一個ServerSocket,用于監(jiān)聽客戶端Socket的連接請求ServerSocket ss = new ServerSocket(30000);//采用循環(huán)不斷接受來自客戶端的請求while (true){//每當(dāng)接受到客戶端Socket的請求,服務(wù)器端也對應(yīng)產(chǎn)生一個SocketSocket s = ss.accept();//下面就可以使用Socket進(jìn)行通信了...}客戶端通常可使用Socket的構(gòu)造器來連接到指定服務(wù)器
Client示例:
//創(chuàng)建連接到服務(wù)器、30000端口的SocketSocket s = new Socket("192.168.2.214" , 30000);//下面就可以使用Socket進(jìn)行通信了...這樣Server和Client就可以進(jìn)行一個簡單的通信了
當(dāng)然,我們要做的是多客戶,所以每當(dāng)客戶端Socket連接到該ServerSocket之后,程序?qū)?yīng)Socket加入clients集合中保存,并為該Socket啟動一條線程,該線程負(fù)責(zé)處理該Socket所有的通信任務(wù)
//定義保存所有Socket的ArrayListpublic static ArrayList<Socket> clients = new ArrayList<Socket>();
當(dāng)服務(wù)器線程讀到客戶端數(shù)據(jù)之后,程序遍歷clients集合,并將該數(shù)據(jù)向clients集合中的每個Socket發(fā)送一次。這樣就可以實(shí)現(xiàn)一個聊天室的功能了
下面來看看整個功能的demo
先建立一個Java工程,把Server.java運(yùn)行起來,然后再運(yùn)行手機(jī)模擬器

服務(wù)器打印信息:

程序文件結(jié)構(gòu):

1.先看看主Activity : SocketmsgActivity.java
public class SocketmsgActivity extends Activity { /** Called when the activity is first created. */ private SQLiteDatabase db; Thread thread = null; Socket s = null; private InetSocketAddress isa = null; DataInputStream dis = null; DataOutputStream dos = null; private String reMsg=null; private Boolean isContect = false; private EditText chattxt; private EditText chatbox; private Button chatok; private String chatKey="SLEEKNETGEOCK4stsjeS"; private String name=null,ip=null,port=null; @Override public void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.main); chattxt = (EditText)findViewById(R.id.chattxt); chatbox = (EditText)findViewById(R.id.chatbox); chatok = (Button)findViewById(R.id.chatOk); chatbox.setCursorVisible(false); chatbox.setFocusable(false); chatbox.setFocusableInTouchMode(false); chatbox.setGravity(2); //初始化,創(chuàng)建數(shù)據(jù)庫來儲存用戶信息 InitDatabase(); db = SQLiteDatabase.openOrCreateDatabase(config.f, null); try { Cursor cursor = db.query("config", new String[]{"ip","name","port"},null,null, null, null, null); while(cursor.moveToNext()){ name = cursor.getString(cursor.getColumnIndex("name")); ip = cursor.getString(cursor.getColumnIndex("ip")); port = cursor.getString(cursor.getColumnIndex("port")); } cursor.close(); } catch (Exception e) { // TODO: handle exception System.out.println(e.toString()); } db.close(); //設(shè)置連接 if(ip==null || port==null){ Intent intent = new Intent(SocketmsgActivity.this,IniActivity.class); startActivity(intent); SocketmsgActivity.this.finish(); } //設(shè)置名稱 else if(name==null){ Intent intent = new Intent(SocketmsgActivity.this,IniuserActivity.class); startActivity(intent); SocketmsgActivity.this.finish(); }else{ connect(); chatok.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { String str = chattxt.getText().toString().trim(); System.out.println(s); try { dos.writeUTF(chatKey+"name:"+name+"end;"+str); chattxt.setText(""); }catch (SocketTimeoutException e) { System.out.println("
主站蜘蛛池模板:
黄冈市|
绵竹市|
怀仁县|
英超|
于田县|
米林县|
湖南省|
乌海市|
沂水县|
中宁县|
凌源市|
福清市|
乐业县|
大化|
新疆|
洛浦县|
图木舒克市|
宁阳县|
枣庄市|
南城县|
蕲春县|
手机|
吉安县|
安平县|
罗山县|
荔浦县|
景东|
安吉县|
登封市|
霍城县|
梅河口市|
普兰店市|
涞水县|
大同县|
蕉岭县|
察哈|
芜湖市|
恩施市|
平昌县|
抚宁县|
永泰县|