新聞中心
java網(wǎng)絡(luò)編程代碼求教
這兩個(gè)六不需要close掉啊,最多是你在搞定之后需要close掉socket啊。
創(chuàng)新互聯(lián)公司主營(yíng)比如網(wǎng)站建設(shè)的網(wǎng)絡(luò)公司,主營(yíng)網(wǎng)站建設(shè)方案,app軟件開(kāi)發(fā),比如h5微信平臺(tái)小程序開(kāi)發(fā)搭建,比如網(wǎng)站營(yíng)銷(xiāo)推廣歡迎比如等地區(qū)企業(yè)咨詢(xún)
這兩個(gè)都是你自己的方法里面的局部變量,在你每次調(diào)用完這個(gè)方法之后,java的資源回收機(jī)制會(huì)自動(dòng)釋放這些資源,不需要你手動(dòng)close。
java網(wǎng)絡(luò)編程
我也才寫(xiě)了一個(gè),我不想看代碼
你可以把發(fā)送和接受信息都寫(xiě)在一個(gè)死循環(huán)里
客戶(hù)端:1.發(fā)送 2.接受
服務(wù)端:1.接受 2.發(fā)送
這個(gè)接收我第一個(gè)代碼用的BufferedRedaer br = new BufferedReader(new InputStreamReader(in))
br.readline();//這個(gè)是阻塞式的,不接受到消息它是不會(huì)往后執(zhí)行的,更ServerSocket里的accept方法一樣的
客戶(hù)端發(fā)送了就會(huì)卡在接受那,而服務(wù)器這邊就會(huì)收到,服務(wù)器就會(huì)執(zhí)行回復(fù)的輸入,回復(fù)輸入后,客戶(hù)端這邊就能接收到,就這樣循環(huán)
第一次寫(xiě)的時(shí)候用的是PrintWriter進(jìn)行發(fā)送,用inputstream的read方法讀出來(lái)會(huì)不對(duì)
printwriter的write方法就是寫(xiě)入緩存,要用到String的getbytes方法,注意要使用flush方法清空緩存
讀取用的是BufferedReader
利用Socket進(jìn)行Java網(wǎng)絡(luò)編程(三)
作者 郗旻 附 服務(wù)器的實(shí)現(xiàn)代碼import *;import java io *;import java awt event ActionEvent;import java awt event ActionListener;public class talkServer{ public static void main(String[] args) { try{ file://建立服務(wù)器 ServerSocket server = new ServerSocket( ); int i= ; for(;;){ Socket ining = server accept() new ServerThread(ining i) start(); i++;} }catch (IOException ex){ ex printStackTrace();} }}class ServerThread extends Thread implements ActionListener{ private int threadNum; private Socket socket; talkServerFrm t; BufferedReader in; PrintWriter out; private boolean talking=true; public ServerThread(Socket s int c) { threadNum = c;socket = s; }public void actionPerformed(ActionEvent e){ Object source = e getSource(); try{if(source==t btnSend) { out println(t getTalk());t clearTalk();}elseif(source==t btnEnd) { out println( 談話(huà)過(guò)程被對(duì)方終止 );out close();in close();talking = false; } }catch(IOException ex){ }}public void run(){ try{t=new talkServerFrm(new Integer(threadNum) toString() this);t setSize( );t show();in = new BufferedReader(new InputStreamReader(socket getInputStream()));out = new PrintWriter(socket getOutputStream() true); }catch(Exception e){} new Thread() { public void run(){ try{while(true){ checkInput(); sleep( );} }catch (InterruptedException ex){ }catch(IOException ex){ } } } start(); while(talking) { } t dispose(); }private void checkInput() throws IOException{ String line; if((line=in readLine())!=null)t setPartner(line); file://這是界面類(lèi)里的方法 file://用來(lái)將line的內(nèi)容輸出到用戶(hù)界面 }} lishixinzhi/Article/program/Java/hx/201311/25829
當(dāng)前文章:java網(wǎng)絡(luò)編程代碼 java是網(wǎng)絡(luò)編程語(yǔ)言
當(dāng)前網(wǎng)址:http://www.ef60e0e.cn/article/dodhcps.html