javasocket客戶端
Ⅰ java socket 客戶端設置未接收到數據的超時問題
建議如果是長時間沒有收到數據的話,或者是不想長時間等待的話,都可以通過設置超時時間來進行斷開連接,之後繼續處理邏輯(設置socket的setSoTimeout方法實現即可,時間單位是毫秒):
packagesocket;
importjava.io.ByteArrayOutputStream;
importjava.io.InputStream;
importjava.net.InetSocketAddress;
importjava.net.ServerSocket;
importjava.net.Socket;
importjava.net.SocketAddress;
importjava.net.SocketException;
importjava.net.SocketTimeoutException;
importjava.text.SimpleDateFormat;
importjava.util.Arrays;
importjava.util.Date;
publicclassSocketService{
publicstaticvoidmain(String[]args){
try{
SocketAddressaddress=newInetSocketAddress("192.168.9.155",3000);
//啟動監聽埠8001
ServerSocketss=newServerSocket();
ss.bind(address);
//接收請求
Sockets=ss.accept();
newThread(newT(s)).start();
}catch(Exceptione){
e.printStackTrace();
}
}
}
classTimplementsRunnable{
publicvoidrun(){
try{
System.out.println(socket.toString());
socket.setKeepAlive(true);
socket.setSoTimeout(5*1000);
String_pattern="yyyy-MM-ddHH:mm:ss";
SimpleDateFormatformat=newSimpleDateFormat(_pattern);
while(true){
System.out.println("開始:"+format.format(newDate()));
try{
InputStreamips=socket.getInputStream();
ByteArrayOutputStreambops=newByteArrayOutputStream();
intdata=-1;
while((data=ips.read())!=-1){
System.out.println(data);
bops.write(data);
}
System.out.println(Arrays.toString(bops.toByteArray()));
}catch(SocketTimeoutExceptione){
e.printStackTrace();
}catch(SocketExceptione){
e.printStackTrace();
}catch(Exceptione){
e.printStackTrace();
}
Thread.sleep(1000);
System.out.println(socket.isBound());//是否邦定
System.out.println(socket.isClosed());//是否關閉
System.out.println(socket.isConnected());//是否連接
System.out.println(socket.isInputShutdown());//是否關閉輸入流
System.out.println(socket.isOutputShutdown());//是否關閉輸出流
System.out.println("結束:"+format.format(newDate()));
}
}catch(Exceptione){
e.printStackTrace();
}
}
privateSocketsocket=null;
publicT(Socketsocket){
this.socket=socket;
}
publicSocketgetSocket(){
returnsocket;
}
publicvoidsetSocket(Socketsocket){
this.socket=socket;
}
}
Ⅱ socket java實現客戶端多線程接受消息並發送消息給伺服器,並發執行
客服端:
package MyKeFudaun;
import java.io.BufferedReader;
import java.io.BufferedWriter;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.OutputStreamWriter;
import java.net.Socket;
import java.net.UnknownHostException;
public class KeFuDuan {
public static void main(String[] args) {
KeFuDuan kf = new KeFuDuan();
kf.start();
}
public void start(){
Socket sco;
String ss= "";
try {
sco = new Socket("127.0.0.1",8866);
KeFuanJie kf = new KeFuanJie(sco);
KeFuWuFasong kfs = new KeFuWuFasong(sco);
kf.start();
kfs.start();
//sco.close();
} catch (UnknownHostException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
class KeFuanJie extends Thread{
Socket soc;
String ss;
BufferedReader br;
public KeFuanJie(Socket soc){
try {
this.soc = soc;
br = new BufferedReader(new InputStreamReader(soc.getInputStream()));
} catch (IOException e) {
e.printStackTrace();
}
}
//負責接受服務端來的信息
public void run(){
while(true){
//接受伺服器端來的信息
try {
ss = br.readLine();
System.out.println("伺服器---->客服端: "+ss);
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
}
//向伺服器發送東西
class KeFuWuFasong extends Thread{
Socket soc;
BufferedWriter bw;
BufferedReader brr;
public KeFuWuFasong(Socket soc){
this.soc = soc;
try {
brr =new BufferedReader(new InputStreamReader(System.in));
bw = new BufferedWriter(new OutputStreamWriter(soc.getOutputStream()));
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
public void run(){
while(true){
//向伺服器發送請求
try {
bw.write(brr.readLine());
bw.newLine();
bw.flush();// 或者用bw.close()
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
}
伺服器端:
package MyKeFudaun;
import java.io.BufferedReader;
import java.io.BufferedWriter;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.OutputStreamWriter;
import java.net.ServerSocket;
import java.net.Socket;
public class Server {
public static void main(String[] args) {
Server server = new Server();
server.start();
}
public void start(){
try { //伺服器端打開埠
ServerSocket server = new ServerSocket(4499);
Socket socket = null;
ServerToClientThread stct = null;
while(true){
socket = server.accept(); //迎接(接收)客戶端的Socket訪問
stct = new ServerToClientThread(socket); //分配一個新線程負責和信賴的Socket溝通
stct.start();
}
} catch (IOException e) {
e.printStackTrace();
}
}
}
package MyKeFudaun;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.net.Socket;
public class ServerReceiveFromClient extends Thread{
Socket socket;
BufferedReader br;
String s;
public ServerReceiveFromClient(Socket socket){
this.socket = socket;
try {
br = new BufferedReader(new InputStreamReader(socket.getInputStream()));
} catch (IOException e) {
e.printStackTrace();
}
}
public void run(){
while(true){
try {
s = br.readLine();
System.out.println(socket.getInetAddress().getHostAddress()+"發送了:"+s);
} catch (Exception e) {
e.printStackTrace();
}
}
}
}
package MyKeFudaun;
import java.io.BufferedReader;
import java.io.BufferedWriter;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.OutputStreamWriter;
import java.net.Socket;
public class ServerToClientThread extends Thread{
Socket socket;
BufferedReader br;
BufferedWriter bw;
String s;
//建立的同時,和客戶端的Socket建立輸入、輸出流
public ServerToClientThread(Socket socket){
this.socket = socket;
try {
bw = new BufferedWriter(new OutputStreamWriter(socket.getOutputStream()));
} catch (IOException e) {
e.printStackTrace();
}
}
public void run(){
ServerReceiveFromClient srfc = new ServerReceiveFromClient(socket);
srfc.start();
while(true){
try {
bw.write("歡迎光臨。");
bw.newLine();
bw.flush();
Thread.sleep(10*1000);
} catch (IOException e) {
e.printStackTrace();
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}
}
Ⅲ java socket 客戶端是如何向伺服器端發送消息的
伺服器端和客戶端都是通過SOCKET來進行通信的,首先產生一個 socket實例,通過這個實例,伺服器端調用accept這個方法接收來自客戶端發送的信息.但是在產生socket實例的時候必須初始化一個埠.用來負責接受客戶端的請求!
客戶端要給伺服器發送消息也必須產生一個socket實例,初始化的時候必須指定伺服器的IP地址,並且指定服務接收的埠號,這樣客戶端才能找到伺服器要接收的地方,找到地方就可以發送過去了。和你寫信一樣。找到地址
BufferedReader in = new BufferedReader(new InputStreamReader(socket.getInputStream()));
PrintWriter out = new PrintWriter(socket.getOutputStream());
BufferedReader wt = new BufferedReader(new InputStreamReader(System.in));
這個只是用來獲取一個從鍵盤的一個流.傳送給伺服器端的數據都是通過流來表示的。意思是是鍵盤輸入的一個位元組轉化成字元流.並輸出或者寫入!
Ⅳ Java Socket中伺服器斷開後,客戶端為什麼沒有拋異常
在客戶端退出之後,會出現socket連接中斷,此時是會拋出異常,在拋出異常時列印中斷的客戶端即可。
1. while(Binput.read()!= -1) 這種方法能判斷出客戶端輸入是否為空,客戶端斷開能跳出死循環,但是得到的數據卻從第二個開始了,所以這方法不適宜。
2. 在死循環中加入以下代碼:
try {
socket.sendUrgentData(0);
} catch (IOException e) {
done= false; //如果拋出了異常,那麼就是斷開連接了 跳出無限循環
}