服务器端
package test;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.PrintStream;
import java.net.ServerSocket;
import java.net.Socket;
public class TestServer {
public static void main(String[] args) {
// TODO Auto-generated method stub
BufferedReader br = null;
PrintStream out = null;
Socket socket = null;
ServerSocket serversocket = null;
try {
//建立服务套接字
serversocket = new ServerSocket(6888);
System.out.println("等待连接");
//得到socket
socket = serversocket.accept();
System.out.println("连接成功");
//得到包装后的输入输出流
br = new BufferedReader(new InputStreamReader(socket.getInputStream()));
out = new PrintStream(socket.getOutputStream());
//读一行数据库
String str = br.readLine();
System.out.println(str);
//写一行数据
str = "你也好啊";
out.println(str);
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} finally{
try {
out.close();
br.close();
socket.close();
serversocket.close();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
}
客户端
package test;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.PrintStream;
import java.net.Socket;
public class TestClient {
public static void main(String[] args) {
// TODO Auto-generated method stub
Socket socket = null;
BufferedReader br = null;
PrintStream out = null;
try {
//连接到服务器
socket = new Socket("localhost",6888);
//获得包装后的输入输出流
br = new BufferedReader(new InputStreamReader(socket.getInputStream()));
out = new PrintStream(socket.getOutputStream());
String str = "服务器,你好";
out.println(str);
str = br.readLine();
System.out.println(str);
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} finally{
try {
out.close();
br.close();
socket.close();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
}