客户端
public class TcpClient {
public static void main(String[] args) {
try {
Socket s=new Socket(InetAddress.getByName("19.1.0.0"),8001);
InputStream ips=s.getInputStream();
BufferedReader brNet=new BufferedReader(new InputStreamReader(ips));
OutputStream ops=s.getOutputStream();
DataOutputStream dos=new DataOutputStream(ops);
BufferedReader byKey=new BufferedReader(new InputStreamReader(System.in));
while(true)
{
String strWord=byKey.readLine();
if(strWord.equalsIgnoreCase("quit"))
{
break;
}
else
{
System.out.println("I want to say:"+strWord);
dos.writeBytes(strWord+System.getProperty("line.separator"));
System.out.println("Sever said:"+brNet.readLine());
}
}
dos.close();
brNet.close();
byKey.close();
s.close();
}
catch(Exception e)
{
e.printStackTrace();
}
}
}
服务端
public class TcpSever2 {
public static void main(String[] args) {
try {
ServerSocket ss=new ServerSocket(8001);
while(true)
{
Socket s=ss.accept();
System.out.println("there is a client");
new Thread(new Worker(s)).start();
}
} catch (Exception e) {
e.printStackTrace();
}
}
}
class Worker implements Runnable{
Socket s;
public Worker(Socket s)
{
this.s=s;
}
public void run()
{
try {
System.out.println("Server people is ready");
InputStream ips=s.getInputStream();
OutputStream ops=s.getOutputStream();
BufferedReader br=new BufferedReader(new InputStreamReader(ips));
DataOutputStream dos=new DataOutputStream(ops);
while(true)
{
String strWord=br.readLine();
System.out.println("client said"+strWord+":"+strWord.length());
if(strWord.equalsIgnoreCase("quit"))
{
break;
}
String strEcho=strWord+"12138";
System.out.println("server said:"+strWord+"----->"+strEcho);
dos.writeBytes(strWord+"----->"+strEcho+System.getProperty("line.separator"));
}
br.close();
dos.close();
s.close();
}catch(Exception e)
{
e.printStackTrace();
}
}
}