//服务器
import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.net.ServerSocket;
import java.net.Socket;
public class Server {
public static void main(String[] arg){
ServerSocket serversocket=null;
Socket socket=null;
InputStream is=null;
ByteArrayOutputStream baos=null;
try {
//服务器地址
serversocket = new ServerSocket(9999);
//等待客户链接
socket=serversocket.accept();
//读取消息
is= socket.getInputStream();
//管道流
baos= new ByteArrayOutputStream();
byte[] buffer = new byte[1024];
int len;
while ((len=is.read(buffer))!=-1){
baos.write(buffer,0,len);
System.out.println(baos.toString());
}
}catch (IOException e){
e.printStackTrace();
}finally {
//关闭资源
if(baos!=null){
try {
baos.close();
}catch (IOException e){
e.printStackTrace();
}
}
if(is!=null){
try{
is.close();
}catch (IOException e) {
e.printStackTrace();
}
}
if(socket!=null)
{
try{
socket.close();
}catch (IOException e) {
e.printStackTrace();
}
}
if(serversocket!=null){
try{
serversocket.close();
}catch (IOException e) {
e.printStackTrace();
}
}
}
}
}
//客户端
import java.io.*;
import java.net.InetAddress;
import java.net.Socket;
public class Client {
public static void main(String[] arg){
Socket socket=null;
PrintWriter out=null;
BufferedReader sin=null;
BufferedReader in=null;
try {
//绑定服务器地址 端口号
InetAddress serverIP = InetAddress.getByName("127.0.0.1");
int port = 9999;
//创建链接
socket = new Socket(serverIP, port);
//标准输入设备构造BufferedReader 对象
sin=new BufferedReader(new
InputStreamReader(System.in));
//由socket获得io对象
out=new PrintWriter(socket.getOutputStream());
in=new BufferedReader(new
InputStreamReader(socket.getInputStream()));
for(String read_line=sin.readLine();!read_line.equals("bye");read_line = sin.readLine()){
//读入字符串输出到Server 显示
out.println(read_line);
out.flush();
System.out.println("Client:"+read_line);
//从Server中读入字符串 显示
System.out.println("Server:"+in.readLine());
}
}catch (Exception e) {
e.printStackTrace();
}finally {
if(in!=null)
{
try{
in.close();
}catch (IOException e) {
e.printStackTrace();
}
}if(sin!=null)
{
try{
sin.close();
}catch (IOException e) {
e.printStackTrace();
}
}if(out!=null)
{
try{
out.close();
}catch (UnknownError e) {
e.printStackTrace();
}
}if(socket!=null){
try{
socket.close();
}catch (IOException e) {
e.printStackTrace();
}
}
}
}
}