java socket类实现在客户端读取来自服务器的普通文本
2个回答
展开全部
给你一个聊天的客户端,希望有用
import java.io.DataInputStream;
import java.io.DataOutputStream;
import java.io.IOException;
import java.net.Socket;
import java.net.UnknownHostException;
import java.util.Scanner;
public class client {
private String over;
private Socket socket;
private DataInputStream in;
public void connect() {
try {
socket = new Socket("192.168.1.101", 9888);
in = new DataInputStream(socket.getInputStream());
DataOutputStream os = new DataOutputStream(socket.getOutputStream());
newThread th = new newThread();
Scanner can = new Scanner(System.in);th.start();
over = "";
while (!over.equals("exit")) {
System.out.println("请输入聊天内容");
String str = can.next();
os.writeUTF(str);
over = str;
}
} catch (UnknownHostException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
public static void main(String args[]) {
new client().connect();
}
class newThread extends Thread {
public void run() {
try {
while (!over.equals("exit")) {
String str = in.readUTF();
System.out.println(str);
over = str;
sleep(1000);
}
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
}
import java.io.DataInputStream;
import java.io.DataOutputStream;
import java.io.IOException;
import java.net.Socket;
import java.net.UnknownHostException;
import java.util.Scanner;
public class client {
private String over;
private Socket socket;
private DataInputStream in;
public void connect() {
try {
socket = new Socket("192.168.1.101", 9888);
in = new DataInputStream(socket.getInputStream());
DataOutputStream os = new DataOutputStream(socket.getOutputStream());
newThread th = new newThread();
Scanner can = new Scanner(System.in);th.start();
over = "";
while (!over.equals("exit")) {
System.out.println("请输入聊天内容");
String str = can.next();
os.writeUTF(str);
over = str;
}
} catch (UnknownHostException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
public static void main(String args[]) {
new client().connect();
}
class newThread extends Thread {
public void run() {
try {
while (!over.equals("exit")) {
String str = in.readUTF();
System.out.println(str);
over = str;
sleep(1000);
}
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
}
追问
不好意思,虽然不符合,但还是谢谢你的帮助
推荐律师服务:
若未解决您的问题,请您详细描述您的问题,通过百度律临进行免费专业咨询