服务端:
public class TerminalServer {
private ServerSocket server;
private Socket client;
private InputStream sin;
private OutputStream sout;
public void create(){
try {
server =new ServerSocket(8989);
} catch (IOException e) {
System.out.println("端口不能被使用");
}
try {
client = server.accept();
sin = client.getInputStream();
sout = client.getOutputStream();
} catch (IOException e) {
e.printStackTrace();
}
}
public void write(String str){
try {
byte []b = str.getBytes("utf-8");
sout.write(b);
sout.flush();
} catch (Exception e) {
e.printStackTrace();
}
}
public void read(){
byte []b = new byte[1024];
try {
sin.read(b);
System.out.println(b[0]);
String str = new String(b, "utf-8");
System.out.println(str);
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
public void close(){
try {
sin.close();
sout.close();
client.close();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
public static void main(String []args){
Scanner scan = new Scanner(System.in);
TerminalServer ts = new TerminalServer();
System.out.println("服务启动");
ts.create();
new Thread(new Runnable() {
@Override
public void run() {
while(true){
ts.read();
}
}
}).start();
new Thread(new Runnable() {
@Override
public void run() {
// TODO Auto-generated method stub
while(true){
String str = scan.nextLine();
ts.write(str);
}
}
}).start();
}
}
-----------------------------------------------------------------------------------------------------
客户端:
public class Client {
private Socket client;
private InputStream cin;
private OutputStream cout;
public static void main(String []args){
Scanner scan = new Scanner(System.in);
Client client = new Client();
client.create("localhost", 8989);
new Thread(new Runnable() {
@Override
public void run() {
while(true){
try {
client.read();
} catch (Exception e) {
System.out.println("连接服务器中断");
break;
}
}
}
}).start();
new Thread(new Runnable() {
@Override
public void run() {
// TODO Auto-generated method stub
while(true){
try{
String str = scan.nextLine();
client.write(str);
}catch(Exception e){
System.out.println("连接服务器中断");
break;
}
}
}
}).start();
}
public void create(String host, int port) {
try {
client = new Socket(host, port);
} catch (Exception e) {
System.out.println("服务器连接失败");
}
try {
cout = client.getOutputStream();
cin = client.getInputStream();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
public void write(String str) throws IOException {
byte[] b = str.getBytes("utf-8");
cout.write(b, 0, b.length);
cout.flush();
}
public void read() throws IOException{
byte []b = new byte[1024];
cin.read(b);
System.out.println(b[0]);
String str = new String(b, "utf-8");
System.out.println(str);
}
public void close(){
try {
cin.close();
cout.close();
client.close();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}