服务器端:
package com.hwp.test.socket;
import java.io.*;
import java.net.*;
public class Service
{
public static final int PORT = 5858;
public void service()
{
ServerSocket server = null;
Socket socket = null;
try
{
server = new ServerSocket(PORT);
socket = server.accept();
BufferedReader in = new BufferedReader(new InputStreamReader(socket
.getInputStream()));
PrintWriter out = new PrintWriter(new BufferedWriter(
new OutputStreamWriter(socket.getOutputStream())), true);
while (true)
{
String str = in.readLine();
System.out.println("server.print:" + str);
if (str.equals("end"))
{
break;
}
out.println(str);
}
}
catch (Exception e)
{
e.printStackTrace();
}
finally
{
if (socket != null)
{
try
{
socket.close();
}
catch (Exception e)
{
e.printStackTrace();
}
}
if (server != null)
{
try
{
server.close();
}
catch (Exception e)
{
e.printStackTrace();
}
}
}
}
public static void main(String args[])
{
Service service = new Service();
service.service();
}
}
客户端:
package com.hwp.test.socket;
import java.io.BufferedReader;
import java.io.BufferedWriter;
import java.io.InputStreamReader;
import java.io.OutputStreamWriter;
import java.io.PrintWriter;
import java.net.Socket;
import java.util.Scanner;
public class Client
{
public void client()
{
Socket socket = null;
try
{
socket = new Socket("127.0.0.1", 5858);
BufferedReader in = new BufferedReader(new InputStreamReader(socket
.getInputStream()));
PrintWriter out = new PrintWriter(new BufferedWriter(
new OutputStreamWriter(socket.getOutputStream())), true);
Scanner scanner = new Scanner(System.in);
while(scanner.hasNextLine())
{
out.println(scanner.nextLine());
System.out.println("client.print:" + in.readLine());
}
}
catch (Exception e)
{
e.printStackTrace();
}
finally
{
if (socket != null)
{
try
{
socket.close();
}
catch (Exception e)
{
e.printStackTrace();
}
}
}
}
public static void main(String ages[])
{
Client client = new Client();
client.client();
}
}