对于java的网络编程以及线程,我用一个例子来记录:
简单的聊天程序实现:
服务端代码:
import java.io.*;
import java.net.*;
import java.util.*;
public class ChatServer {
ArrayList clientOutputStreams;
public class ClientHandler implements Runnable
{
BufferedReader reader;//使用BufferedReader不用数据串流来自文件或者Socket
Socket sock;
public ClientHandler(Socket clientSocket)
{
try {
sock = clientSocket;
InputStreamReader isReader = new InputStreamReader(sock.getInputStream());
reader = new BufferedReader(isReader);
} catch (Exception e) {
e.printStackTrace();
}
}
public void run() {
String message;
try {
while ((message = reader.readLine()) != null)
{
System.out.println("read "+message);
tellEveryone(message);
}
} catch (Exception e) {
e.printStackTrace();
}
}
}
public static void main(String[] args) {
new ChatServer().go();
}
public void go(){
clientOutputStreams = new ArrayList();
try {
ServerSocket serverSocket = new ServerSocket(5000);
while (true) {
Socket clientSocket = serverSocket.accept();
PrintWriter writer = new PrintWriter(clientSocket.getOutputStream());
clientOutputStreams.add(writer);
Thread t = new Thread(new ClientHandler(clientSocket));
t.start();
System.out.println("got a connection");
}
} catch (Exception e) {
e.printStackTrace();
}
}
public void tellEveryone(String message){
Iterator it = clientOutputStreams.iterator();
while (it.hasNext()) {
try {
PrintWriter writer = (PrintWriter)it.next();
writer.println(message);
writer.flush();
} catch (Exception e) {
e.printStackTrace();
}
}
}
}
客户端代码:
import java.awt.BorderLayout;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.io.*;
import java.net.Socket;
import javax.swing.*;
public class SimpleChartClient {
JTextArea incoming;
JTextField outgoing;
BufferedReader reader;
PrintWriter writer;
Socket socket;
public static void main(String[] args) {
SimpleChartClient client = new SimpleChartClient();
client.go();
}
public void go()
{
JFrame frame = new JFrame("简单的聊天客户端!");
JPanel mainPanel = new JPanel();
incoming = new JTextArea(15,50);
incoming.setLineWrap(true);
incoming.setWrapStyleWord(true);
incoming.setEditable(false);
JScrollPane qScroller = new JScrollPane(incoming);
qScroller.setVerticalScrollBarPolicy(ScrollPaneConstants.VERTICAL_SCROLLBAR_ALWAYS);
qScroller.setHorizontalScrollBarPolicy(ScrollPaneConstants.HORIZONTAL_SCROLLBAR_NEVER);
outgoing = new JPasswordField(20);
JButton sendBtn = new JButton("发送");
sendBtn.addActionListener(new SenderBtnListener());
mainPanel.add(qScroller);
mainPanel.add(outgoing);
mainPanel.add(sendBtn);
setUpNetWorking();
Thread readerThread = new Thread(new IncomingReader());
readerThread.start();
frame.getContentPane().add(BorderLayout.CENTER,mainPanel);
frame.setSize(400,500);
frame.setVisible(true);
}
public void setUpNetWorking()
{
try {
socket = new Socket("127.0.0.1",5000);
InputStreamReader streamReader = new InputStreamReader(socket.getInputStream());
reader = new BufferedReader(streamReader);
writer = new PrintWriter(socket.getOutputStream());
System.out.println("NetWorking established!");
} catch (Exception e) {
e.printStackTrace();
}
}
public class SenderBtnListener implements ActionListener
{
public void actionPerformed(ActionEvent e) {
try {
writer.println(outgoing.getText());
writer.flush();
} catch (Exception exception) {
exception.printStackTrace();
}
outgoing.setText("");
outgoing.requestFocus();
}
}
public class IncomingReader implements Runnable
{
public void run() {
String message;
try {
while ((message = reader.readLine())!=null)
{
System.out.println("read "+message);
incoming.append(message+"\n");
}
} catch (Exception e) {
e.printStackTrace();
}
}
}
}
线程的执行流程
1.建立Runnable对象(线程的任务)
Runnable threadJob = new MyRunnable();
实现接口Runnable中的抽象方法run(),执行run方法就是执行线程的任务。
2.建立Thread对象(执行工人)并赋值Runnable(任务)
Thread myThread = new Thread(threadJob);
把Runnable对象传给Thread构造方法。
3.启动线程(Thread)
myThread.start();
调用Thread的start()方法之前线程什么也不会做,线程启动后会把Runnable对象的方法放到执行空间里。