客户端
import java.net .Socket
import java.io .InputStream
import java.io .InputStreamReader
import java.io .BufferedReader
import java.io .OutputStream
import java.util .Scanner
public class Client{
public static void main(String []args){
try{
Socket s=new Socket("127.0.0.1" ,6666 )
InputStream in =s.getInputStream ()
OutputStream out =s.getOutputStream ()
InputStreamReader read=new InputStreamReader(in )
BufferedReader br=new BufferedReader(read)
Scanner sca=new Scanner(System.in )
while(true){
System.out .println ("请您输入一串字符" )
String str=sca.next ()
String strmessage=str+System.getProperty ("line.separator" )
byte []bs=strmessage.getBytes ()
out .write (bs)
if(str.equals ("quit" )){
break
}
String message=br.readLine ()
System.out .println (message)
}
in .close ()
out .close ()
s.close ()
}catch(Exception ex){
}
}
}
服务端
import java.net.Socket;
import java.io.InputStream;
import java.io.OutputStream;
import java.io.InputStreamReader;
import java.io.BufferedReader;
import java.io.DataOutputStream;
public class Server implements Runnable {
private Socket s;
public Server (Socket s){
this .s=s;
}
public void run (){
try {
InputStream in=s.getInputStream();
OutputStream out=s.getOutputStream();
InputStreamReader read=new InputStreamReader(in);
BufferedReader br=new BufferedReader(read);
DataOutputStream ds=new DataOutputStream(out);
while (true ){
String str=br.readLine();
if (str.equals("quit" )){
break ;
}
StringBuffer sb=new StringBuffer(str);
String strehco=sb.reverse().toString();
ds.writeBytes(strehco+System.getProperty("line.separator" ));
}
in.close();
out.close();
s.close();
}catch (Exception ex){
System.out.println(ex.getMessage());
}
}
}
测试服务端,每接收一次请求,就开启一个线程
import java.net.ServerSocket;
import java.net.Socket;
public class TcpServer{
public static void main (String []args){
try {
ServerSocket ss=new ServerSocket(6666 );
while (true ){
Socket s=ss.accept();
Server server=new Server(s);
new Thread(server).start();
}
}catch (Exception ex){
System.out .println(ex.getMessage());
}
}
}