简单的client/server程序
TestServer.java
import java.net.*;
import java.io.*;
public class TestServer {
public static void main(String args[]) {
try {
ServerSocket s = new ServerSocket(8888);
while (true) {
Socket s1 = s.accept();
OutputStream os = s1.getOutputStream();
DataOutputStream dos = new DataOutputStream(os);
dos.writeUTF("Hello," + s1.getInetAddress() + "port#" + s1.getPort() + " bye-bye!");
dos.close();
s1.close();
}
} catch (IOException e) {
e.printStackTrace();
System.out.println("程序运行出错:" + e);
}
}
}
TestClient.java
import java.net.*;
import java.io.*;
public class TestClient {
public static void main(String args[]) {
try {
Socket s1 = new Socket("127.0.0.1", 8888);
InputStream is = s1.getInputStream();
DataInputStream dis = new DataInputStream(is);
System.out.println(dis.readUTF());
dis.close();
s1.close();
} catch (ConnectException connExc) {
connExc.printStackTrace();
System.err.println("服务器连接失败!");
} catch (IOException e) {
e.printStackTrace();
}
}
}
TCP实现控制台输入
- 读懂,有不足的地方,第四个里面会讲
- 实现了控制台手动输入
talkserver.java
import java.io.*;
import java.net.*;
public class talkserver {
public static void main(String args[]) {
try {
ServerSocket server = null;
try {
server = new ServerSocket(4700);
} catch (Exception e) {
System.out.println("can not listen to:" + e);
}
Socket socket = null;
try {
socket = server.accept();
} catch (Exception e) {
System.out.println("Error:" + e);
}
String line;
BufferedReader is = new BufferedReader(new InputStreamReader(socket.getInputStream()));
PrintWriter os = new PrintWriter(socket.getOutputStream());
BufferedReader sin = new BufferedReader(new InputStreamReader(System.in));
System.out.println("Client:" + is.readLine());
line = sin.readLine();
while (!line.equals("bye")) {
os.println(line);
os.flush();
System.out.println("Server:" + line);
System.out.println("Client:" + is.readLine());
line = sin.readLine();
}
is.close();
os.close();
socket.close();
server.close();
} catch (Exception e) {
System.out.println("Error" + e);
}
}
}
talkclient.java
import java.io.*;
import java.net.*;
public class talkclient {
public static void main(String args[]) {
try {
Socket socket = new Socket("127.0.0.1", 4700);
BufferedReader sin = new BufferedReader(new InputStreamReader(System.in));
PrintWriter os = new PrintWriter(socket.getOutputStream());
BufferedReader is = new BufferedReader(new InputStreamReader(socket.getInputStream()));
String readline;
readline = sin.readLine();
while (!readline.equals("bye")) {
os.println(readline);
os.flush();
System.out.println("Client:" + readline);
System.out.println("Server:" + is.readLine());
readline = sin.readLine();
}
os.close();
is.close();
socket.close();
} catch (Exception e) {
System.out.println("Error" + e);
}
}
}
TestUDP
TestUDPServer.java
import java.net.*;
public class TestUDPServer {
public static void main(String args[]) throws Exception {
byte buf[] = new byte[1024];
DatagramPacket dp = new DatagramPacket(buf, buf.length);
DatagramSocket ds = new DatagramSocket(5678);
while (true) {
ds.receive(dp);
System.out.println(new String(buf, 0, dp.getLength()));
}
}
}
TestUDPClient.java
import java.net.*;
public class TestUDPClient {
public static void main(String args[]) throws Exception {
byte[] buf = (new String("Hello")).getBytes();
DatagramPacket dp = new DatagramPacket(buf, buf.length, new InetSocketAddress("127.0.0.1", 5678));
DatagramSocket ds = new DatagramSocket(9999);
ds.send(dp);
ds.close();
}
}
TestUDP 发送长整形数据
- 可以用于游戏中坐标的传递
- UDP没有严格意义上的Server和Client区分
TestUDPServer.java
import java.net.*;
import java.io.*;
public class TestUDPServer
{
public static void main(String args[]) throws Exception
{
byte buf[] = new byte[1024];
DatagramPacket dp = new DatagramPacket(buf, buf.length);
DatagramSocket ds = new DatagramSocket(5678);
while(true)
{
ds.receive(dp);
ByteArrayInputStream bais = new ByteArrayInputStream(buf);
DataInputStream dis = new DataInputStream(bais);
System.out.println(dis.readLong());
}
}
}
TestUDPClient.java
import java.net.*;
import java.io.*;
public class TestUDPClient {
public static void main(String args[]) throws Exception {
long n = 10000L;
ByteArrayOutputStream baos = new ByteArrayOutputStream();
DataOutputStream dos = new DataOutputStream(baos);
dos.writeLong(n);
byte[] buf = baos.toByteArray();
System.out.println(buf.length);
DatagramPacket dp = new DatagramPacket(buf, buf.length, new InetSocketAddress("127.0.0.1", 5678));
DatagramSocket ds = new DatagramSocket(9999);
ds.send(dp);
ds.close();
}
}
Chat1.0图形界面版
ChatServer.java
import java.net.*;
import java.util.*;
import java.io.*;
import java.awt.*;
import java.awt.event.*;
public class ChatServer extends Frame
{
TextArea ta = new TextArea();
public void launchFrame()
{
add(ta, BorderLayout.CENTER);
setBounds(0,0,200,300);
this.addWindowListener(
new WindowAdapter()
{
public void windowClosing(WindowEvent e)
{
System.exit(0);
}
}
);
setVisible(true);
}
ServerSocket server = null;
Collection cClient = new ArrayList();
public ChatServer(int port) throws Exception
{
server = new ServerSocket(port);
launchFrame();
}
public void startServer() throws Exception
{
while(true)
{
Socket s = server.accept();
cClient.add( new ClientConn(s) );
ta.append("NEW-CLIENT " + s.getInetAddress() + ":" + s.getPort());
ta.append("\n" + "CLIENTS-COUNT: " + cClient.size() + "\n\n");
}
}
class ClientConn implements Runnable
{
Socket s = null;
public ClientConn(Socket s)
{
this.s = s;
(new Thread(this)).start();
}
public void send(String str) throws IOException
{
DataOutputStream dos = new DataOutputStream(s.getOutputStream());
dos.writeUTF(str);
}
public void dispose()
{
try {
if (s != null) s.close();
cClient.remove(this);
ta.append("A client out! \n");
ta.append("CLIENT-COUNT: " + cClient.size() + "\n\n");
}
catch (Exception e)
{
e.printStackTrace();
}
}
public void run()
{
try {
DataInputStream dis = new DataInputStream(s.getInputStream());
String str = dis.readUTF();
while(str != null && str.length() !=0)
{
System.out.println(str);
for(Iterator it = cClient.iterator(); it.hasNext(); )
{
ClientConn cc = (ClientConn)it.next();
if(this != cc)
{
cc.send(str);
}
}
str = dis.readUTF();
}
this.dispose();
}
catch (Exception e)
{
System.out.println("client quit");
this.dispose();
}
}
}
public static void main(String[] args) throws Exception
{
ChatServer cs = new ChatServer(8888);
cs.startServer();
}
}
ChatClient.java
import java.io.*;
import java.net.*;
import java.awt.*;
import java.awt.event.*;
public class ChatClient extends Frame {
TextArea ta = new TextArea();
TextField tf = new TextField();
public void launchFrame() throws Exception {
this.add(ta, BorderLayout.CENTER);
this.add(tf, BorderLayout.SOUTH);
tf.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent ae) {
try {
String sSend = tf.getText();
if (sSend.trim().length() == 0)
return;
ChatClient.this.send(sSend);
tf.setText("");
ta.append(sSend + "\n");
} catch (Exception e) {
e.printStackTrace();
}
}
});
this.addWindowListener(new WindowAdapter() {
public void windowClosing(WindowEvent e) {
System.exit(0);
}
});
setBounds(300, 300, 300, 400);
setVisible(true);
tf.requestFocus();
}
Socket s = null;
public ChatClient() throws Exception {
s = new Socket("127.0.0.1", 8888);
launchFrame();
(new Thread(new ReceiveThread())).start();
}
public void send(String str) throws Exception {
DataOutputStream dos = new DataOutputStream(s.getOutputStream());
dos.writeUTF(str);
}
public void disconnect() throws Exception {
s.close();
}
public static void main(String[] args) throws Exception {
BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
ChatClient cc = new ChatClient();
String str = br.readLine();
while (str != null && str.length() != 0) {
cc.send(str);
str = br.readLine();
}
cc.disconnect();
}
class ReceiveThread implements Runnable {
public void run() {
if (s == null)
return;
try {
DataInputStream dis = new DataInputStream(s.getInputStream());
String str = dis.readUTF();
while (str != null && str.length() != 0) {
ChatClient.this.ta.append(str + "\n");
str = dis.readUTF();
}
} catch (Exception e) {
e.printStackTrace();
}
}
}
}
在线聊天系统雏形
- Chat1.0的完善
- 最后的end还讲了Server类中如何再开线程正确去除和监视Client,区分ip和端口,注册名字,但没代码实现
- 多线程处理多个客户端连接
- 比较完美的程序
- 先开服务器,再开客户端
- 多线程利用的很好
- 讲解Server端删除关闭的Client端抓取异常
- Client端的connect(),disconnect(),run()方法是重点
- Server端的start(),send()抓异常,run()方法抓异常,send()抛异常给run()方法
ChatServer.java
import java.io.*;
import java.net.*;
import java.util.*;
public class ChatServer {
boolean started = false;
ServerSocket ss = null;
ArrayList<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.out.println("请关掉相关程序并重新运行服务器");
System.exit(0);
} catch (IOException e) {
System.out.println("服务器启动失败");
}
try {
while(started) {
Socket s = ss.accept();
Client c = new Client(s);
System.out.println("a client connecten");
new Thread(c).start();
clients.add(c);
}
} catch (IOException e) {
e.printStackTrace();
} finally {
try {
ss.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
class Client implements Runnable{
private Socket s;
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());
bConnected = true;
} catch (IOException e) {
e.printStackTrace();
}
}
public void send(String str) {
try {
dos.writeUTF(str);
} catch (IOException e) {
clients.remove(this);
System.out.println("对方退出了,我从list中去除了");
}
}
public void run() {
try {
while (bConnected) {
String str = dis.readUTF();
System.out.println(str);
for(int i = 0; i < clients.size(); i++) {
Client c = clients.get(i);
c.send(str);
System.out.println("a string send !");
}
}
}
catch (EOFException e) {
System.out.println("Client closed");
} catch (IOException e) {
e.printStackTrace();
} finally {
try {
if(dis != null) dis.close();
if(dos != null) dos.close();
if(s != null) {
s.close();
s = null;
}
} catch (IOException e1) {
e1.printStackTrace();
}
}
}
}
}
ChatClient.java
import java.awt.*;
import java.awt.event.*;
import java.io.*;
import java.net.*;
public class ChatClient extends Frame{
Socket s;
DataOutputStream dos = null;
DataInputStream dis = null;
private boolean bConnected = false;
TextField tfText = new TextField();
TextArea taContent = new TextArea();
Thread tRecv = new Thread(new RecvThread());
public static void main(String[] args) {
new ChatClient().launchFrame();
}
public void launchFrame() {
setLocation(100, 100);
setSize(800, 600);
setBackground(Color.green);
add(taContent, BorderLayout.NORTH);
add(tfText, BorderLayout.SOUTH);
pack();
addWindowListener(new WindowAdapter() {
public void windowClosing(WindowEvent e) {
disconnect();
System.exit(0);
}
});
tfText.addActionListener(new TFListener());
setVisible(true);
connect();
tRecv.start();
}
public void connect() {
try {
s = new Socket("127.0.0.1", 8888);
dos = new DataOutputStream(s.getOutputStream());
dis = new DataInputStream(s.getInputStream());
System.out.println("connected");
bConnected = true;
} catch (IOException e) {
e.printStackTrace();
}
}
public void disconnect() {
try {
dos.close();
dis.close();
s.close();
} catch (IOException e) {
e.printStackTrace();
}
}
private class TFListener implements ActionListener {
public void actionPerformed(ActionEvent e) {
String str = tfText.getText().trim();
tfText.setText("");
try {
dos.writeUTF(str);
dos.flush();
} catch (IOException e1) {
e1.printStackTrace();
}
}
}
private class RecvThread implements Runnable {
public void run() {
try {
while(bConnected) {
String str = dis.readUTF();
taContent.setText(taContent.getText() + str + "\n");
}
} catch (SocketException e) {
System.out.println("退出了, bye!");
} catch (EOFException e) {
System.out.println("退出了,bye - bye");
} catch (IOException e) {
e.printStackTrace();
}
}
}
}