向单个客户端应用添加线程

时间:2013-01-23 17:02:10

标签: java sockets client-server

这是我的TCPClient代码。我想添加线程并使其成为一个多客户端程序。这样2个TCPClient就可以与服务器通信。我怎么能这样做?

import java.io.*;
import java.net.*;

class TCPClient extends Thread
{
 public static void main(String argv[]) throws Exception
 {
  String sentence;
  String modifiedSentence;
  BufferedReader inFromUser = new BufferedReader( new InputStreamReader(System.in));
  Socket clientSocket = new Socket("localhost", 6789);
  DataOutputStream outToServer = new DataOutputStream(clientSocket.getOutputStream());
  BufferedReader inFromServer = new BufferedReader(new InputStreamReader(clientSocket.getInputStream()));
  sentence = inFromUser.readLine();
  outToServer.writeBytes(sentence + '\n');
  modifiedSentence = inFromServer.readLine();
  System.out.println("FROM SERVER: " + modifiedSentence);
  clientSocket.close();
 }
}

0 个答案:

没有答案