展开全部
//服务端程序:
import java.io.*;
import java.net.*;
public class TCPServer {
public static void main(String[] args) throws IOException {
new TCPServer().init();
}
@SuppressWarnings("static-access")
private void init() throws IOException{
@SuppressWarnings("resource")
ServerSocket server = new ServerSocket(1000);
Socket client = null;
while(true){
try {
client = server.accept();
BufferedInputStream bis = new BufferedInputStream(client.getInputStream());
byte[] b = new byte[1024];
int len = 0;
String message = "";
while((len=bis.read(b))!=-1){
message = new String(b,0,len);
System.out.print("客户端:32313133353236313431303231363533e78988e69d8331333335333761"+client.getInetAddress().getLocalHost().getHostAddress()+"发来消息:" + message);
if("byte".equals(message.trim()))
client.close();
PrintWriter pw = new PrintWriter(client.getOutputStream(),true);
pw.println(message);
}
} catch (Exception e) {
System.err.println("客户端:"+client.getInetAddress().getLocalHost().getHostAddress()+" 已断开连接!");
}
}
}
}//客户端程序:
import java.io.*;
import java.net.Socket;
public class TCPClient implements Runnable{
public static void main(String[] args) throws IOException {
new TCPClient().init();
}
private void init() throws IOException{
@SuppressWarnings("resource")
final Socket client = new Socket("127.0.0.1",1000);
BufferedReader in = new BufferedReader(new InputStreamReader(System.in));
String send = "";
while(true){
send = in.readLine();
PrintWriter out = new PrintWriter(client.getOutputStream(),true);
if(!"byte".equals(send.trim()))
out.println(send);
else{
out.println(send);
System.exit(0);
}
new Thread(new TCPClient(){
@SuppressWarnings("static-access")
public void run(){
try {
BufferedInputStream bis = new BufferedInputStream(client.getInputStream());
byte[] b = new byte[1024];
int len = 0;
while((len=bis.read(b))!=-1){
System.out.println("服务器:" +client.getInetAddress().getLocalHost().getHostAddress()+"发来消息:"+new String(b,0,len).trim());
}
} catch (IOException e) {
System.err.println("连接服务器失败!");
}
}
}).start();
}
}
public void run() {}
}
//服务器测试结果:
客户端:192.168.0.200发来消息:001 byte
客户端:192.168.0.200发来消息:byte
客户端:192.168.0.200 已断开连接!
客户端:192.168.0.200发来消息:adasd
客户端:192.168.0.200 已断开连接!
//客户端测试结果:
---001号客户端--
001 byte
服务器:192.168.0.200发来消息:001 byte
byte //001礼貌说跟服务器说byte
---002号客户端--
adasd //002客户端直接关闭程序
服务器:192.168.0.200发来消息:adasd