- public class TCPClient2
- {
- public static void main(String[] args) throws UnknownHostException, IOException
- {
- Socket bothSocket = new Socket("127.0.0.1",10005);
- Send2 send = new Send2(bothSocket);
- Receive2 receive = new Receive2(bothSocket);
-
- new Thread(send).start();
- new Thread(receive).start();
-
- }
- }
- //创建发送和接收的类,使用多线程,继承runnable接口
- //多线程发送类
- class Send2 implements Runnable{
- private Socket s;
- OutputStream os;
- public Send2(Socket s) throws IOException {
- super();
- this.s = s;
- os = s.getOutputStream();
- }
- @Override
- public void run()
- {
- BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
- String line = null;
- try {
- while((line = br.readLine()) != null){
-
- os.write(line.getBytes());
-
- if("//over".equals(line)){
- break;
- }
- }
- s.close();
- } catch (IOException e) {
- }
- }
- }
- //多线程接收类
- class Receive2 implements Runnable{
- private Socket s;
-
- private InputStream is;
- public Receive2(Socket s) throws IOException {
- super();
- this.s = s;
- }
- @Override
- public void run()
- {
- while(true){
- byte[] buf = new byte[1024];
- try {
- is = s.getInputStream();
- int len = is.read(buf);
- String str = new String(buf,0,len);
- if("//over".equals(str)){
- break;
- }
- System.out.println(str);
- s.close();
- } catch (IOException e) {
- }
- }
- }
- }