package com.panpass.main;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.OutputStream;
import java.io.PrintWriter;
import java.net.ServerSocket;
import java.net.Socket;
import java.net.UnknownHostException;
public class ServerTest {
private int port = 8080;
private ServerSocket serverSocket = null;
public ServerTest() throws UnknownHostException, IOException {
super();
serverSocket = new ServerSocket(port);
System.out.println("服务端启动。");
}
public PrintWriter getWriter(Socket socket) throws IOException{
OutputStream os = socket.getOutputStream();
return new PrintWriter(os,true);
}
public BufferedReader getReader(Socket socket) throws IOException{
InputStream is = socket.getInputStream();
return new BufferedReader(new InputStreamReader(is));
}
public void service(){
while(true){
Socket socket = null;
try {
socket = serverSocket.accept(); // 等待客户端请求数据
BufferedReader br = getReader(socket);
PrintWriter pw = getWriter(socket);
String msg = null;
while((msg = br.readLine()) != null){
System.out.println("服务端收到:"+msg);
pw.println("服务端响应:"+msg);
if("bye".equals(msg)){
break;
}
}
} catch (IOException e) {
e.printStackTrace();
}finally{
if(socket != null){
try {
socket.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
}
}
public static void main(String[] args) throws UnknownHostException, IOException {
new ServerTest().service();
}
}
<pre name="code" class="html">package com.panpass.main;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.OutputStream;
import java.io.PrintWriter;
import java.net.Socket;
import java.net.UnknownHostException;
/**
* 客户端程序
* @author Administrator
*
*/
public class ClientTest {
private String host = "localhost";
private int port = 8080;
private Socket socket = null;
public ClientTest() throws UnknownHostException, IOException {
super();
socket = new Socket(host, port);
}
public PrintWriter getWriter(Socket socket) throws IOException{
OutputStream os = socket.getOutputStream();
return new PrintWriter(os,true);
}
public BufferedReader getReader(Socket socket) throws IOException{
InputStream is = socket.getInputStream();
return new BufferedReader(new InputStreamReader(is));
}
public void talk() {
try {
BufferedReader br = getReader(socket);
PrintWriter pw = getWriter(socket);
BufferedReader localBr = new BufferedReader(new InputStreamReader(System.in));
String msg = null;
while((msg = localBr.readLine()) != null){
pw.println(msg);
System.out.print("客户端收到:"+br.readLine());
if(msg.equals("bye")){
break;
}
}
} catch (IOException e) {
e.printStackTrace();
}finally{
if(socket != null){
try {
socket.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
}
public static void main(String[] args) throws UnknownHostException, IOException {
new ClientTest().talk();
}
}