这是在一本java教材上看到的,做了点修改。具体本教材记不清楚了,Sorry.放在这里,只是让自己需要的时候能够容易找到。
程序分两部分,服务端和客户端。先把服务端运行起来,在运行客户端。整个过程就是客户端想服务端发送String,服务端再返回。客户端的String由键盘输入得到。 服务器端。- package net.tcp;
- 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 extends Thread
- {
- ServerSocket server = null;
- Socket sk = null;
- BufferedReader rdr = null;
- PrintWriter wtr = null;
- public Server()
- {
- try
- {
- server = new ServerSocket(1987);
- }
- catch (IOException e)
- {
- e.printStackTrace();
- }
- }
- public void run()
- {
- while (true)
- {
- System.out.println("Listenning...");
- try
- {
- // 每个请求交给一个线程去处理
- sk = server.accept();
- ServerThread th = new ServerThread(sk);
- th.start();
- sleep(1000);
- }
- catch (Exception e)
- {
- e.printStackTrace();
- }
- }
- }
- public static void main(String [] args)
- {
- new Server().start();
- }
- class ServerThread extends Thread
- {
- Socket sk = null;
- public ServerThread(Socket sk)
- {
- this.sk = sk;
- }
- public void run()
- {
- try
- {
- wtr = new PrintWriter(sk.getOutputStream());
- rdr = new BufferedReader(new InputStreamReader(sk
- .getInputStream()));
- String line = rdr.readLine();
- System.out.println("从客户端来的信息:" + line);
- // 特别,下面这句得加上 “\n”,
- wtr.println("你好,服务器已经收到您的信息!'" + line + "'\n");
- wtr.flush();
- System.out.println("已经返回给客户端!");
- }
- catch (IOException e)
- {
- e.printStackTrace();
- }
- }
- }
- }
客户端:
- package net.tcp;
- import java.io.BufferedReader;
- import java.io.BufferedWriter;
- import java.io.InputStreamReader;
- import java.io.OutputStreamWriter;
- import java.io.PrintWriter;
- import java.net.Socket;
- public class Client extends Thread
- {
- Socket sk = null;
- BufferedReader reader = null;
- PrintWriter wtr = null;
- BufferedReader keyin = null;
- public Client()
- {
- keyin = new BufferedReader(new InputStreamReader(System.in));
- try
- {
- sk = new Socket("127.0.0.1", 1987);
- }
- catch (Exception e)
- {
- e.printStackTrace();
- }
- }
- public void run()
- {
- try
- {
- reader = new BufferedReader(new InputStreamReader(sk
- .getInputStream()));
- wtr = new PrintWriter(sk.getOutputStream());
- String get = keyin.readLine();
- while (true)
- {
- if (get != null & get.length() > 0)
- {
- wtr.println(get);
- wtr.flush();
- // wtr.close();
- // System.out.println(get + "发送完毕");
- }
- if (reader != null)
- {
- String line = reader.readLine();
- System.out.println("从服务器来的信息:" + line);
- }
- }
- }
- catch (Exception e)
- {
- e.printStackTrace();
- }
- }
- public static void main(String [] args)
- {
- new Client().start();
- }
- }