服务器类
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.OutputStream;
import java.net.InetAddress;
import java.net.ServerSocket;
import java.net.Socket;
import java.net.UnknownHostException;
public class TCPServer {
private int port;
public TCPServer(int port) {
super();
this.port = port;
Recevice recevice=new Recevice();
Thread server=new Thread(recevice);
server.start();
}
public static void main(String[] args) {
new TCPServer(10001);
}
class Recevice implements Runnable {
public void run() {
ServerSocket ss = null;
Socket s=null;
BufferedReader br=null;
try {
System.out.println("服务器启动");
ss = new ServerSocket(port);
s = ss.accept();
InputStream is = s.getInputStream();
br=new BufferedReader(new InputStreamReader(is));
InetAddress ia = s.getInetAddress();
String ip = ia.getHostAddress();
String str=null;
while((str=br.readLine())!=null){
System.out.println(ip+" say : "+str);
}
} catch (IOException e) {
e.printStackTrace();
}
finally{
try {
if(br!=null)
br.close();
if(s!=null)
s.close();
if(ss!=null)
ss.close();
} catch (IOException e2) {
e2.printStackTrace();
}
}
}
}
}
客户端类
import java.io.BufferedReader;
import java.io.BufferedWriter;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.OutputStream;
import java.io.OutputStreamWriter;
import java.net.Socket;
import java.net.UnknownHostException;
public class TCPClient{
private String ip;
private int port;
public TCPClient(String ip, int port) {
super();
this.ip = ip;
this.port = port;
Sender sender=new Sender();
Thread t=new Thread(sender);
t.start();
}
class Sender implements Runnable{
@Override
public void run() {
Socket socket=null;
BufferedReader br=null;
BufferedWriter bw=null;
try {
socket=new Socket(ip,port);
br=new BufferedReader(new InputStreamReader(System.in));
OutputStream os = socket.getOutputStream();
bw=new BufferedWriter(new OutputStreamWriter(os));
String str=null;
while((str=br.readLine())!=null){
bw.write(str);
bw.newLine();
bw.flush();
}
} catch (UnknownHostException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
finally{
try {
if(bw!=null)
bw.close();
if(br!=null)
br.close();
if(socket!=null)
socket.close();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
}
}
测试类
public class ChatRoom {
public static void main(String[] args) {
new TCPClient("172.20.10.9", 10001);
}
}