socket p to p

package socket;


import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.PrintWriter;
import java.net.ServerSocket;
import java.net.Socket;


public class Server {
public static void main(String[] args) {
ServerSocket server = null;
Socket soc = null;
BufferedReader dis = null;
PrintWriter ps = null;
String clientSay = null;
try {
server = new ServerSocket(8001);
System.out.println("wait.....");
soc = server.accept();
System.out.println("finish connection!");
dis = new BufferedReader(new InputStreamReader(soc.getInputStream()));
ps = new PrintWriter(soc.getOutputStream(),true);
ps.println("Welcome!");
clientSay = dis.readLine();
while(!clientSay.equals("quit")){
System.out.println("client say:"+clientSay);
clientSay = dis.readLine();
}
System.out.println("client quit!");
} catch (IOException e) {
System.out.println("Error:"+e);
}finally{

try {
ps.close();
dis.close();
soc.close();
server.close();
} catch (IOException e) {
e.printStackTrace();
}

}
}


}

==========================================================

package socket;


import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.PrintWriter;
import java.net.Socket;
import java.net.UnknownHostException;


public class Client {
public static void main(String[] args) {
Socket soc = null;
BufferedReader br = null;
PrintWriter pw = null;
BufferedReader sys = null;
String sysStr = null;
try {
System.out.println("start connection...");
soc = new Socket("127.0.0.1",8001);
br = new BufferedReader(new InputStreamReader(soc.getInputStream()));
pw = new PrintWriter(soc.getOutputStream(),true);
sys = new BufferedReader(new InputStreamReader(System.in));
System.out.println("Server say:"+br.readLine());
sysStr = sys.readLine();
while(!sysStr.equals("quit")){
pw.println(sysStr);
sysStr = sys.readLine();
}
pw.println(sysStr);
} catch (UnknownHostException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}finally{
try {
sys.close();
pw.close();
br.close();
soc.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}


}

發佈了4 篇原創文章 · 獲贊 2 · 訪問量 2萬+
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章