ServerSocket會建立port口,供客戶端接入。之後的 server.accept() 就會接收客戶端的連接(注意: ServerSocket 的 accept() 方法是阻塞式的,就是說如果沒有客戶端接入,整個程式就不會run下去 )
客戶端就會這樣接入:
並且會開啟兩個Thread給客戶端
localhost就是你的本機IP
源碼:
Server端:dis.readUTF() 接收客戶端傳來的信息
dos.writeUTF() 傳出信息到客戶端
dos.flush() 強制刷新dos
注意:使用了writeUTF()傳出就必須用readUTF()接收
Client:
(線程)Send:
package tcp.socket2;
import java.io.BufferedReader;
import java.io.DataOutputStream;
import java.io.IOException;
import java.io.InputStreamReader;
import java.net.Socket;
public class Send implements Runnable{
private BufferedReader console;
private DataOutputStream dos;
private boolean isRun = true;
public Send() {
console = new BufferedReader(new InputStreamReader(System.in));
}
public Send(Socket client) {
this();
try{
dos = new DataOutputStream(client.getOutputStream());
} catch (IOException e) {
e.printStackTrace();
isRun = false;
//closeUntil.closeAll(dos, console);
}
}
private String getMsg() {
try {
return console.readLine();
} catch (IOException e) {
e.printStackTrace();
}
return "";
}
public void send() throws IOException {
String msg = getMsg();
if (null != msg && !msg.equals("")){
dos.writeUTF(msg);
dos.flush();
}
}
@Override
public void run() {
while (isRun){
try {
send();
} catch (IOException e) {
e.printStackTrace();
}
}
}
}
(線程)recevie:
package tcp.socket2;
import java.io.DataInputStream;
import java.io.IOException;
import java.net.Socket;
public class receive implements Runnable {
DataInputStream dis;
private boolean isRun = true;
public receive(Socket client) throws IOException {
dis = new DataInputStream(client.getInputStream());
}
public String receiver() throws IOException {
String msg = dis.readUTF();
return msg;
}
@Override
public void run() {
while (isRun){
try {
System.out.println(receiver());
} catch (IOException e) {
e.printStackTrace();
}
}
}
}
完成後效果就是這樣了:
注意:一定要先開服務器再開客戶端
連接成功時:
在Server端輸入:
客戶端就會顯示:
在客戶端輸入:
Server端就會顯示:
這樣就完成了服務器與客戶端互相聯繫了
No comments:
Post a Comment