服务端
package com.softeem.TTP;
import java.io.DataInputStream;
import java.io.DataOutputStream;
import java.io.IOException;
import java.net.ServerSocket;
import java.net.Socket;
import java.util.Currency;
import java.util.Scanner;
import javax.swing.JOptionPane;
public class Test4_Server {
public static void main(String[] args) throws IOException {
ServerSocket ss = new ServerSocket(8888);
System.out.println("等待客户连接。。。。");
Socket s = ss.accept();
System.out.println("连接成功");
Message1 sm = new Message1(s);
new Thread(sm, "发送").start();
new Thread(sm, "接收").start();
}
}
class Message1 implements Runnable {
private Socket s;
public Message1(Socket s) {
this.s = s;
}
public void run() {
String name = Thread.currentThread().getName();
if(Thread.currentThread().getName().equals("发送")){
try {
write();
} catch (IOException e) {
e.printStackTrace();
}
}else{
try {
read();
} catch (IOException e) {
e.printStackTrace();
}
}
}
public void read() throws IOException{
while(true){
DataInputStream dis = new DataInputStream(s.getInputStream());
System.out.println("从客户端读取了"+dis.readUTF());
}
}
public void write() throws IOException{
while(true){
DataOutputStream dos = new DataOutputStream(s.getOutputStream());
String str = JOptionPane.showInputDialog("请输入要发送的信息");
System.out.println("服务器:"+str);
dos.writeUTF(str);
}
}
}
客户端
package com.softeem.TTP;import java.io.DataInputStream;
import java.io.DataOutputStream;
import java.io.IOException;
import java.io.WriteAbortedException;
import java.net.ServerSocket;
import java.net.Socket;
import java.util.Scanner;import javax.swing.JOptionPane;public class Test4_Client {public static void main(String[] args) throws IOException {
Socket s = new Socket("localhost",8888);
Message2 am = new Message2(s);
new Thread(am,"接受").start();
new Thread(am,"发送").start();}
}
class Message2 implements Runnable {
private Socket s ;
public Message2(Socket s ) {
this.s= s;
} public void run() {
if(Thread.currentThread().getName().equals("发送")){
try {
write();
} catch (IOException e) {
e.printStackTrace();
}
}else{
try {
read();
} catch (IOException e) {
e.printStackTrace();
}
}
}
public void read() throws IOException{
while(true){
DataInputStream dis = new DataInputStream(s.getInputStream());
System.out.println("服务器"+dis.readUTF());
}
}
public void write() throws IOException {
while(true){
DataOutputStream dos = new DataOutputStream(s.getOutputStream());
String str = JOptionPane.showInputDialog("请输入发送的信息");
System.out.println("客户端:"+str);
dos.writeUTF(str);
}
}
}