需求是这样的
制作一个客户端 要求程序启动开始建立连接 程序关闭 断开连接1.每10秒向服务端发送一段数据2.服务端不定期发送数据到客户端 客户端打印出来 3.数据可能在向服务端发送数据的同时 由服务端发送给客户端ps:目前我自己实现了10秒向服务端发送数据,但是无法接收到服务端不定期向客户端发送的数据请各位高手帮帮忙,本人由于没做过网络编程 所以不是很熟悉。
制作一个客户端 要求程序启动开始建立连接 程序关闭 断开连接1.每10秒向服务端发送一段数据2.服务端不定期发送数据到客户端 客户端打印出来 3.数据可能在向服务端发送数据的同时 由服务端发送给客户端ps:目前我自己实现了10秒向服务端发送数据,但是无法接收到服务端不定期向客户端发送的数据请各位高手帮帮忙,本人由于没做过网络编程 所以不是很熟悉。
import java.net.*;
import java.util.*;public class ChatServer
{
private ServerSocket ss = null;
private boolean started = false;
List<Client> clients = new ArrayList<Client>();
public static void main(String[] args)
{
new ChatServer().start();
}
//运行服务器端
public void start()
{
try
{
ss = new ServerSocket(8888);
started = true;
}
catch(BindException e)
{
System.out.println("端口已经被使用......");
System.exit(0);
}
catch(IOException e)
{
e.printStackTrace();
}
try
{
while(started)
{
Socket s = ss.accept();
Client c = new Client(s);
//开启一个接收和发送数据给客户端的线程 ,并将这个线程放到集合里面
new Thread(c).start();
clients.add(c);
System.out.println("一个客户端链接上!");
}
}
catch(EOFException e)
{
System.out.println("客户端已经关闭!");
}
catch(IOException e)
{
e.printStackTrace();
}
finally
{
try
{
ss.close();
}
catch (IOException e)
{
e.printStackTrace();
}
}
}
//和客户端通讯的内部类(线程)
class Client implements Runnable
{
private Socket s = null;
private DataInputStream dis = null;
private DataOutputStream dos = null;
private boolean bConnected = false;
public Client(Socket s)
{
this.s = s;
try
{
dis = new DataInputStream(s.getInputStream());
dos = new DataOutputStream(s.getOutputStream());
}
catch (IOException e)
{
e.printStackTrace();
}
}
//发送数据到客户端的方法
public void sent(String str)
{
try
{
dos.writeUTF(str);
dos.flush();
}
catch (IOException e)
{
clients.remove(this);
System.out.println("对方已经退出 !从LIST中删除!");
}
}
@Override
public void run()
{
bConnected = true;
try
{
while(bConnected)
{
String str = dis.readUTF();
for(int i=0; i<clients.size();i++)
{
Client c = clients.get(i);
c.sent(str);
}
}
}
catch(EOFException e)
{
System.out.println("客户端已经关闭!");
}
catch(IOException e)
{
e.printStackTrace();
}
finally
{
try
{
if(dis != null)
{
dis.close();
}
if(dos != null)
{
dos.close();
}
if(s != null)
{
s.close();
}
}
catch (IOException e)
{
e.printStackTrace();
}
}
}
}
}
import java.awt.event.*;
import java.net.*;
import java.io.*;public class ChatClient extends Frame
{
TextField tfTxt = new TextField();
TextArea taContent = new TextArea();
Socket s = null;
DataOutputStream dos = null;
DataInputStream dis = null;
boolean bConnected = false;
public static void main(String[] args)
{
ChatClient cc = new ChatClient();
cc.launchFrame();
}
public void launchFrame()
{
this.setLocation(300,400);
this.setSize(300,300);
add(taContent,BorderLayout.NORTH);
add(tfTxt,BorderLayout.SOUTH);
addWindowListener(
new WindowAdapter()
{
public void windowClosing(WindowEvent e)
{
disconnect();
System.exit(0);
}
});
tfTxt.addActionListener(new TFListener());
pack();
this.setVisible(true);
connect();
new Thread(new ReceiveMsg()).start();
}
public void connect()
{
try
{
s = new Socket("liuning",8888);
dos = new DataOutputStream(s.getOutputStream());
dis = new DataInputStream(s.getInputStream());
bConnected = true;
System.out.println("连接了!");
}
catch(IOException e)
{
e.printStackTrace();
}
}
public void disconnect()
{
try
{
if(dos != null)
{
dos.close();
}
if(dis != null)
{
dis.close();
}
if(s != null)
{
s.close();
}
}
catch (IOException e)
{
e.printStackTrace();
}
} private class TFListener implements ActionListener
{
@Override
public void actionPerformed(ActionEvent e)
{
String str = tfTxt.getText().trim();
tfTxt.setText("");
try
{
dos.writeUTF(str);
dos.flush();
}
catch(IOException err)
{
err.printStackTrace();
}
}
}
private class ReceiveMsg implements Runnable
{
@Override
public void run()
{
String str;
try
{
while(bConnected)
{
str = dis.readUTF();
taContent.setText(taContent.getText() + str + "\n");
}
}
catch (IOException e)
{
System.out.println("客户端退出");
}
}
}
}
public class ReceiveThread extends Thread {
private Socket socket;
public ReceiveThread(Socket socket) {
this.socket = socket;
} public void run() {
try {
String line = "";
DataInputStream dis = new DataInputStream(socket.getInputStream());
while (true) {
System.out.println("ReceiveThread:" + dis.available());
if (dis.available()>0) { System.out.println("input: " + dis.readUTF());
}
Thread.sleep(1000);
}
} catch (Exception ex) {
System.out.println(ex);
} }
}
现在可以正常读出dis.available()但是无法读取内容 ,谁帮帮忙啊 着急 谢谢~
public class SampleClient { public static void main(String[] args) throws IOException, InterruptedException {
Socket s = new Socket("127.0.0.1",2000);
BufferedReader br = new BufferedReader(new InputStreamReader(s.getInputStream()));
PrintWriter pw = new PrintWriter(new BufferedWriter(new OutputStreamWriter(s.getOutputStream())), true);
// 接收数据线程
new ClientRecieve(br);
int i = 0;
while (!s.isClosed()) {
// 客户端每2秒发送数据到服务器
pw.println("client sending: " + i++);
Thread.sleep(2000);
}
}
}
public class ClientRecieve extends Thread { private BufferedReader br;
public ClientRecieve(BufferedReader br) {
this.br = br;
this.start();
}
public void run() {
for (;;) {
try {
System.out.println("client recieved: " + br.readLine());
} catch (IOException e) {
e.printStackTrace();
}
}
}
}
public ThreadTest() {
} public static void main(String[] args) {
Socket socket=null;;
try {
socket = new Socket("192.168.2.89", 30451);
} catch (UnknownHostException ex) {
} catch (IOException ex) {
}
SendThread st=new SendThread(socket);
st.start();//每10秒发送数据
ReceiveThread rt=new ReceiveThread(socket);
rt.start();//接收数据
}
}
发送数据类public class SendThread extends Thread {
private Socket socket;
public SendThread(Socket socket) {
this.socket = socket; } public void run() {
OutputStream Os;
try {
while(true){
Os = socket.getOutputStream(); //输出
System.out.println("SendThread run");
byte[] b = new byte[597];
b[0] = (byte) 0xC1;
b[1] = (byte) 0x9F;
b[2] = (byte) 0xC4;
b[3] = (byte) 0x00;
b[4] = (byte) 0x00;
b[5] = (byte) 0x44;
b[6] = (byte) 0x84;
Os.write(b);
Os.flush();
Thread.sleep(10000);
}
} catch (Exception e) {
System.out.println("Error:" + e);
} }}
接收数据public class ReceiveThread extends Thread {
private Socket socket;
public ReceiveThread(Socket socket) {
this.socket = socket;
}
public void run() {
try {
DataInputStream dis = new DataInputStream(socket.getInputStream()); while (true) {
System.out.println("ReceiveThread:" + dis.available());
System.out.println("input UTF: " + dis.readUTF());
if (dis.available()>0) { System.out.println("input: " + dis.read());
System.out.println("input Boolean: " + dis.readBoolean());
System.out.println("input Byte: " + dis.readByte());
System.out.println("input Char: " + dis.readChar());
System.out.println("input Double: " + dis.readDouble());
System.out.println("input Float: " + dis.readFloat());
System.out.println("input Int: " + dis.readInt());
System.out.println("input Long: " + dis.readLong());
System.out.println("input Short: " + dis.readShort());
System.out.println("input UTF: " + dis.readUTF());
}
Thread.sleep(1000);
}
} catch (Exception ex) {
System.out.println(ex);
} }
}
就是接收不到
BufferedReader br = new BufferedReader(new InputStreamReader(socket.getInputStream()));
while (true) {
int i = br.read();
System.out.print((char) i);
}
} catch (Exception ex) {
ex.printStackTrace();
}这样读不出吗?那见鬼咯
还有 怎么
int i = br.read();
System.out.print((char) i);转化一个字符串呢?
服务端
package demo;import java.io.DataInputStream;
import java.io.DataOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.net.ServerSocket;
import java.net.Socket;
import java.util.LinkedList;
import java.util.List;public class Server {
private ServerSocket ss = null; private List<Socket> list = new LinkedList<Socket>(); private class ReceiveThread extends Thread {
private Socket socket = null; public ReceiveThread(Socket socket) {
super("ReceiveThread");
this.socket = socket;
} @Override
public void run() {
InputStream in = null;
DataInputStream dis = null;
while (true) {
try {
sleep(50);
} catch (InterruptedException e1) {
e1.printStackTrace();
} if (socket == null || socket.isClosed()
|| !socket.isConnected()) {
continue;
}
try {
in = socket.getInputStream();
dis = new DataInputStream(in);
String readUTF = dis.readUTF();
System.out.println("receive client message :" + socket
+ " " + readUTF);
send(readUTF);
} catch (IOException e) {
try {
in.close();
dis.close();
} catch (IOException e1) {
e1.printStackTrace();
}
list.remove(socket);
e.printStackTrace();
}
} }
} public void send(String msg) throws IOException {
for (int i = 0; i < list.size(); i++) {
Socket groupSocket = list.get(i);
OutputStream out = groupSocket.getOutputStream();
DataOutputStream dout = new DataOutputStream(out);
dout.writeUTF(msg);
dout.flush();
out.flush();
}
} public class AcceptSocketThread extends Thread {
public AcceptSocketThread() {
super("AcceptSocketThread");
} public void run() {
try {
ss = new ServerSocket(7788); while (true) {
Socket socket = ss.accept();
list.add(socket);
new ReceiveThread(socket).start();
}
} catch (IOException e) {
e.printStackTrace();
} }
} private void start() throws IOException {
new AcceptSocketThread().start();
} public static void main(String[] args) throws Exception {
System.out.println("Server start ....");
new Server().start();
}}
客户端
package demo;import java.io.DataInputStream;
import java.io.DataOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.net.InetAddress;
import java.net.Socket;
import java.util.Scanner;public class Client {
private Socket socket = null; private class ReceiveThread extends Thread {
@Override
public void run() {
while (true) {
try {
InputStream in = socket.getInputStream();
DataInputStream din = new DataInputStream(in);
String readUTF = din.readUTF();
System.out.println("Server Send Message: " + readUTF); } catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
} public void start() throws IOException {
socket = new Socket(InetAddress.getByName("127.0.0.1"), 7788); new ReceiveThread().start();
System.out.println("Client start ....\nPlease input message : ");
while (true) {
Scanner scaner = new Scanner(System.in);
String next = scaner.next();
OutputStream out = socket.getOutputStream();
DataOutputStream dout = new DataOutputStream(out);
dout.writeUTF(next);
// scaner.close();
dout.flush();
}
} public static void main(String[] args) throws IOException {
System.out.println("client ...");
Client client = new Client();
client.start();
}}