可能存在的问题:
发送中文几次后会接收不到消息
思路:
创建接收消息线程 一直等待监听
用Scanner暂时阻塞tcp连接建立
package com.qidai.unit1;
import java.io.IOException;
import java.io.OutputStream;
import java.net.InetAddress;
import java.net.Socket;
import java.util.Scanner;
public class Client {
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
Thread t = new Thread(new SocketReveiceThread());
t.start();
try {
while(true){
//目标端口的主机和ID
String str = sc.nextLine();
Socket s = new Socket(InetAddress.getByName("qidai"), 7777);
OutputStream os = s.getOutputStream();
os.write(str.getBytes());
os.flush();
}
} catch (IOException e) {
e.printStackTrace();
}
}
}
package com.qidai.unit1;
import java.io.IOException;
import java.io.InputStream;
import java.net.ServerSocket;
import java.net.Socket;
public class SocketReveiceThread implements Runnable{
@Override
public void run() {
try {
System.out.println("接收消息已开启");
ServerSocket ss = new ServerSocket(7777);//接收消息端口号
while(true){
byte[] bytes = new byte[50];
Socket s = ss.accept();
InputStream is = s.getInputStream();
is.read(bytes,0,bytes.length);
System.out.println(new String(bytes,"UTF-8"));
}
} catch (IOException e) {
e.printStackTrace();
}
}
}