⭐ 欢迎来到虫虫下载站! | 📦 资源下载 📁 资源专辑 ℹ️ 关于我们
⭐ 虫虫下载站

📄 example1103_tcpserver.java

📁 使用TCP实现两个进程间的通信 (编写客户端与服务器端的Java程序)
💻 JAVA
字号:
import java.awt.*;
import java.awt.event.*;
import javax.swing.*;
import java.net.*;
import java.io.*;

public class Example1103_TCPServer extends JFrame implements Runnable
{
	JTextField hostfield;
	JTextField portfield;
	JTextArea result;
	JLabel status;
	Socket socket=null;
	int port=5678;
	
	public Example1103_TCPServer()
	{
		super("TCP-Server");
		
		setDefaultCloseOperation(EXIT_ON_CLOSE);
		
		Container con=getContentPane();
		
		hostfield=new JTextField();
		portfield=new JTextField(String.valueOf(port));
		result=new JTextArea();
		status=new JLabel("ok");
		
		hostfield.setEditable(false);
		portfield.setEditable(false);
		result.setEditable(false);
		
		Box box=Box.createHorizontalBox();
		box.add(new JLabel("本机地址"));
		box.add(hostfield);
		box.add(new JLabel("监听端口"));
		box.add(portfield);
		
		con.add(box,"North");
		con.add(new JScrollPane(result),"Center");
		con.add(status,"South");
		
		setBounds(0,0,getToolkit().getScreenSize().width,getToolkit().getScreenSize().height/2-20);
		setVisible(true);
		
		Listen();
	}
	
	public void Listen()
	{
		status.setText("ok");

		try
		{
			ServerSocket server=new ServerSocket(port);
			hostfield.setText(InetAddress.getLocalHost().toString());
			while (true)
			{
				socket=server.accept();
				Thread client=new Thread(this);
				client.start();
			}
		}
		catch (UnknownHostException e)
		{
			status.setText("UnknownHostException");
		}
		catch (IOException e)
		{
			status.setText("IOException");
		}
		catch (NumberFormatException e)
		{
			status.setText("NumberFormatException");
		}
	}
	
	public void run()
	{
		status.setText("ok");

		try
		{
			DataInputStream in=new DataInputStream(socket.getInputStream());
			DataOutputStream out=new DataOutputStream(socket.getOutputStream());
			out.writeUTF("Ok");
			String inmes=in.readUTF();
			result.append("Receive: "+inmes+" from "+socket.getLocalAddress()+"\n");
			in.close();
			out.close();
			socket.close();
		}
		catch (UnknownHostException e)
		{
			status.setText("UnknownHostException");
		}
		catch (IOException e)
		{
			status.setText("IOException");
		}
		catch (NumberFormatException e)
		{
			status.setText("NumberFormatException");
		}
	}
	
	public static void main(String[] args)
	{
		new Example1103_TCPServer();
	}
}

⌨️ 快捷键说明

复制代码 Ctrl + C
搜索代码 Ctrl + F
全屏模式 F11
切换主题 Ctrl + Shift + D
显示快捷键 ?
增大字号 Ctrl + =
减小字号 Ctrl + -